Wednesday, 15 February 2012

c++ - Pointer to local variable -



c++ - Pointer to local variable -

may have acces local variable in different function? if may, how?

void replacenumberandprint(int array[3]) { printf("%i\n", array[1]); printf("%i\n", array[1]); } int * getarray() { int myarray[3] = {4, 65, 23}; homecoming myarray; } int main() { replacenumberandprint(getarray()); }

the output of piece of code above:

65 4202656

what doing wrong? "4202656" means??

do have re-create whole array in replacenumberandprint() function able access more first times?

myarray local variable , pointer valid until end of scope (which in case containing function getarray) left. if access later undefined behavior.

in practice happens phone call printf overwrites part of stack used myarray , contains other data.

to prepare code need either declare array in scope lives long enough(the main function in example) or allocate on heap. if allocate on heap need free either manually, or in c++ using raii.

one alternative missed(probably best 1 here) wrap array struct , create value type. returning creates re-create survives function return. see tp1's reply details on this.

c++ c pointers local-variables

No comments:

Post a Comment