In your code, returnArray
returns a pointer to the first element of myArray
, which is local to the function. When the function returns, the memory of its local variables gets released as the call stack is popped, so it can be used for other purposes. In this case, since you call printArray
afterwards, the stack area originally occupied by returnArray
gets reused for printArray
, so the memory that originally contained myArray
now has unpredictable content.
As James Kanze pointed out, the best way to accomplish what you want would probably be to use std::vector<int>
instead of int*
, something like this
std::vector<int> returnArray()
{
int myArray[5] = { 1, 2, 3, 4, 5 };
std::vector<int> result(myArray, myArray + 5);
return result
}
And modify the other functions accordingly to take a vector. Note that in printArray
you need myVector[0]
to access the first element, as vectors aren't pointers.