int* getPtrToArray(int& m)
{
int anArray[5] = { 5, 4, 3, 2, 1 };
m = 5;
return anArray;
}
void f()
{
int junk[100];
for (int k = 0; k < 100; k++)
junk[k] = 123400000 + k;
}
int main()
{
int n;
int* ptr = getPtrToArray(n);
f();
for (int i = 0; i < n; i++)
cout << ptr[i] << ' ';
cout << endl;
}
This is designed to print 5 4 3 2 1. I know it doesnt, and I know how to fix it with a different for loop in main, but I am trying to figure out why this doesnt work and what effect f() has on the pointer. Since the pointer is technically pointing at anArray[0], why does the function f() mess it up?
You're returning the address of a local variable from getPtrToArray(). And the local variable of a function cease to exist when it returns.
Either use a static variable (I would only think of using this if the data in the array was fixed, in which case it would be better const)
1 2 3 4 5 6 7
int* getPtrToArray(int& m)
{
// static variables stay around when a function exits
staticint anArray[5] = { 5, 4, 3, 2, 1 };
m = sizeof(anArray)/sizeof(anArray[0]); // get the compiler to work out size for you
return anArray;
}
Or allocate memory on the heap with new, e.g. int* parray = newint[5];, copy your data into that array, and then return it. In this case you will need to delete the array after use (delete [] parray;).
Andy
(Actually, old local variables may lurk around a bit after a function returns, depending on what happens next in your program, so sometimes a program works ok for a while before dying. But you can't assume the values are valid as the compiler if free to reuse the memory for other purposes (e.g. another function call) whenever it want, after the function does out of scope.
int* getPtrToArray(int& m)
{
int anArray[5] = { 5, 4, 3, 2, 1 };
m = 5;
return anArray;
}
variable anArray is local and will be destroed when the function ends, so you returning pointer to deallocated memory. junk array will be created at the same place, where anArray was (this is how stack work). To get around this you need to create anArray in heap instead on stack. Like that:
1 2 3 4 5 6
int* getPtrToArray(int& m)
{
int* anArray = newint[5]{ 5, 4, 3, 2, 1 };
m = 5;
return anArray;
}
note, that you will need to manually delete allocated memory in this case