C++ : pointers to stack-dynamic variables -
C++ : pointers to stack-dynamic variables -
i new c++. don't quite understand why code not work. code have stack-dynamic variable? help.
int twice(int x) { int *y; *y = x * 2; homecoming *y; }
int *y; *y = x * 2;
is not right because y
points nowwhere, not allocated memory. undefined behavior. after line of code programme unpredictable , cannot assume behavior.
you need allocate memory first using new
or malloc
, assign x*2 or pass address assign y into, i.e:
int *y = new int( x * 2);
example:
int main() { int x = 4; int *y = new int( x * 2); cout << x << "," << *y; delete y; homecoming 0; }
side note: unsafe homecoming pointer memory allocated in function because might become unclear , when responsible freeing allocated memory. in particular case there absolutely no apparent reason dynamic allocation way.
c++
Comments
Post a Comment