My questions are marked in code comments in the snippet below.
int *foo(){
int a = 10;
int b = 20;
return &b;
}
int *foo2(){
int aa = 44;
int bb = 40;
return &bb;
}
int main(int argc, char* argv[])
{
int *p = foo();
int *p2 = foo2();
int a = 700;
int *b = & a;
// cout<<*b<<endl; /* what & why the difference from adding & removing this line?? */
cout<<a<<endl;
cout<<*p<<endl; /* what & why happened to "p" */
return 0;
}
In
foo()andfoo2()you are returning pointers to local variables. These locals have automatic storage and it is undefined behavior to use a pointer to them once they go out of scope. Thereforpandp2contain nothing useful. It might work, it might not.I can’t understand your question very well, so I hope I got it all.