Before I attempt to answer the questions in the comments of your code snippet, let's step through this:
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();
In both foo()
and foo2()
, you're returning a pointer to something located in the function call stack (that is, a
, b
, aa
, and bb
), which will go away when the function returns. Within the function a pointer to variables a
or b
in foo()
or a pointer to variables aa
or bb
in foo2()
will point to something valid.
But when the function returns, those variables will cease to exist. So in both of these functions the returned pointer will not be valid, and consequently p
and p2
will be invalid as well.
int a = 700;
int *b = &a;
You're assigning the address of the variable a
to pointer b
.
// cout<<*b<<endl; /* what & why the difference from adding & removing this line?? */
Adding the line will dereference b
and print out the value of the pointee (in this case, the value of variable a
which is 700).
cout<<*p<<endl; /* what & why happened to "p" */
Since p
is invalid as explained earlier, it will invoke undefined behavior, meaning anything can happen. That can include it working just fine (which I doubt), printing garbage values, crash outright, or explode your computer. Just don't try to dereference an invalid pointer.