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;
}
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
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
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.