0

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;
}
4
  • Could you clarify what you mean by "How is the address of ptr generated?"? ptr is just a local variable. How its "address is generated" is no different than how the addresses of any of the other local variables you're using are determined. On typical systems, it's just the next available location on the stack. Commented Oct 4, 2021 at 23:35
  • 1
    ptr is a variable. It has both a value (representing a pointer to pointer to int) and an address where it is located in memory. Commented Oct 4, 2021 at 23:37
  • Taking the address of a pointer with the & operator is exactly the same as taking the address of any other variable. Commented Oct 4, 2021 at 23:38
  • I wasn't aware that when you declare a function, the argument is also treated as a variable and thus given a value and an address in the memory. Thanks for the answers! Commented Oct 4, 2021 at 23:46

1 Answer 1

1

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 "&".

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the thing that I missed. I didn't know that the function argument is treated as a local variable and declared in the stack. Thank you for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.