c++ - Reference to pointer issue? -
this have:
void g(int *&x) { int = 3; x = &a; } void h(const int *&x) { int b = 2; x = &b; } int main() { int *p = new int; *p = 5; g(p); cout << p << " " << *p << endl; // print #2 cout << p << " " << *p << endl; // print #3 const int*p1 = p; h(p1); cout << p << " " << *p << endl; // print #4 cout << p << " " << *p << endl; // print #5 }
from understand, print#2
, print#3
should have same result isn't when compile it. goes print#4
andprint#5
too. can me?
updated : output looks when compiled on computer:
00eff9d4 3 //1 00eff9d4 1552276352 //2 00eff9d4 2 //3 00eff9d4 1552276352 //4
shouldn't (1) , (2) same ? (3) , (4) either.
i assume mean int a
in g()
.
your function make pointer point a local variable, after termination of function, go out of scope.
you dereference pointer, invokes undefined behavior.
Comments
Post a Comment