0

Why doesn't a pointer work if I initialize the pointer variables later?

See my comment

15th Aug 2022, 5:22 PM
Hajra Khattak
Hajra Khattak - avatar
2 Respostas
+ 5
Syntax for a single pointer declaration is : <type> *<ptr_name> ; Initialization is < ptr_name > = <address of variable>; Like ex : int n = 5; int *ptr; ptr = &n; You can combine like : int *ptr = &n; *ptr returns value; ptr points to location; so *ptr = &n ; is incompatibles. int *ptr = &n ; is valid. // initialization at the time of declaration... If you want reassign, use ptr = &n; no * (dereference operator) . note : pointer can hold address of another variable. this is it's purpose to use it. ptr refers to address, *ptr refers to value stored at the address. Hope it helps..
15th Aug 2022, 6:13 PM
Jayakrishna 🇮🇳
0
// I declare and define pointer variable in a single line #include <iostream> using namespace std; int main() { int value = 5; int *firstP = &value; int **secondP = &firstP; int ***thirdP = &secondP; cout << firstP << endl; cout << secondP << endl; cout << thirdP << endl; cout << ***thirdP << endl; return 0; } it's working well but if i initialize it later then the code doesn't work. int value = 5; int *firstP; int **secondP; int ***thirdP; *firstP = &value; **secondP = &firstP; ***thirdP = &secondP; cout << firstP << endl; cout << secondP << endl; cout << thirdP << endl; cout << ***thirdP << endl; 👆 In this case it is not working. Why?
15th Aug 2022, 5:23 PM
Hajra Khattak
Hajra Khattak - avatar