0
Why doesn't a pointer work if I initialize the pointer variables later?
See my comment
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..
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?