Double pointer confusion

I am studing pointers and I am a little confused,when I am cout the addres ones the second print is 55 ( as normal),but if I add the second address cout
the last print is crazy 73456364
Why is that ,
Also if anybody knows usefull website with questions with pointers and solutions ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

void change(int **i)
{
    int input=55;
    *i=&input;
}
int main(){

int *ptr;
cout<<"Address of ptr "<<&ptr<<endl;
change(&ptr);
cout<<"Address of ptr "<<&ptr<<endl;
cout <<*ptr;


}
You have to dereference a pointer to a pointer twice to get a value.
Thanks for the answer
But if I remove the second cout Address
I am geting the value perfectly fine
Look in void change not in int main
Still confused ,could you please explainde in details
Thanks
I can't tinker with it right now, but my instincts are telling me that *i = &input; is not doing what you think it is.
Why is that ,
On line 5 you're assigning a pointer to a local variable. This local variable becomes invalid as soon as the program leaves the scope (of the function change) hence the value after calling change() is invalid

EDIT: if you get 55 or something else depends on the condition of the stack
Last edited on
closed account (z05DSL3A)
Hmm, the input variable will be trashed after the function returns.
I am confused with ** (double pointer)
I thought that I am changing *ptr,and it is working like that
But when I add line 12 (If this line doesnt exist everithing is fine)
otherwise is printing crazy number
Thanks
You are not changing *ptr. You are changing ptr.

What you are changing it to is the address of a local variable input When the function change returns the variable input goes out of scope. What this means is that the address you assigned to ptr is no longer pointing to an area of memory that you have permission to access, and using that value results in undefined behavior.

local variables like input are generally allocated via the stack. When you make a function call at line 12, it reuses the stack memory that was holding the input variable, so the value will not be what you expected. If you leave line 12 out, *ptr is evaluated before the call to cout on line 13, so the memory hasn't yet been written over when you access it.

Try leaving line 12 out and doing cout << *ptr ; twice.

Topic archived. No new replies allowed.