I’m expecting the code below to print 1 but its printing a random large number.
I don’t understand why this is happening, please advise.
#include <iostream>
using namespace std;
int * returnArray()
{
int myArray[5]={1,2,3,4,5};
return myArray;
}
void printArray(int * myArray)
{
cout << *myArray<< endl;
}
int main()
{
printArray(returnArray());
}
In your code,
returnArrayreturns a pointer to the first element ofmyArray, 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 callprintArrayafterwards, the stack area originally occupied byreturnArraygets reused forprintArray, so the memory that originally containedmyArraynow 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 ofint*, something like thisAnd modify the other functions accordingly to take a vector. Note that in
printArrayyou needmyVector[0]to access the first element, as vectors aren’t pointers.