How to access a local variable from a different function using pointers?

myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.

In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.

To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.

One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1‘s answer for details on this.

Leave a Comment