I am a beginner to c and I've written this example code to help myself understand pointer to pointer as well as call by reference. I understood pretty much everything except for myFunc
: cout << &ptr << endl; // 0x7ffeefbff4d8
I was hoping to get some clarification on this line. Since we are treating the address passed in as the value of a pointer to pointer, aka int** ptr
. How is the address of ptr
generated? Is ptr
somehow implicitly intialized? Thanks in advance!
void myFunc(int** ptr)
{
cout << ptr << endl; // 0x7ffeefbff520
int b = 20;
*ptr = &b;
cout << &ptr << endl; // 0x7ffeefbff4d8
cout << &b << endl; // 0x7ffeefbff4d4
cout << *ptr << endl; // 0x7ffeefbff4d4
return;
}
int main()
{
int *p;
int a = 10;
p = &a;
cout << &a << endl; // 0x7ffeefbff51c
cout << p << endl; // 0x7ffeefbff51c
cout << *p << endl; // 10
cout << &p << endl; // 0x7ffeefbff520
myFunc(&p);
cout << *p << endl; // 20
return 0;
}
CodePudding user response:
When you declare a function such as
void myFunc(int** ptr)
…you actually declare an argument which, even being a pointer to pointer to an int, remains passed by value. Consequently, it's treated like a local variable that would be declared at top of your function.
This variable is therefore declared in the stack, and this is the address you get when using "&".