I was wondering why main() doesn't output 5 4 3 2 1?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int* getPtrToArray(int& m)
{
int anArray[5] = { 5, 4, 3, 2, 1 };
m = 5;
return anArray;
}
int main()
{
int n;
int* ptr = getPtrToArray(n);
for (int i = 0; i < n; i++)
cout << ptr[i] << ' ';
}
It seems to spew some garbage values when run from the for loop, but it seems to return the correct values when the value of an element of ptr is outputted like this, for the first and only time:
cout << ptr[0] << endl; //ptr[1], ptr[2] also output the appropriate values
I understand that arrays are different from pointers in which arrays are constant pointers. So does that mean when I'm returning a constant pointer as a normal pointer, it gets modified immediately?
Does it have to do with the fact that arrays have fixed sizes and memory locations, and regular pointers don't?
If so, what process causes the values of ptr to become garbage after anArray is returned as a regular pointer?
it prints garbage because on line 3 you declare anArray locally which is destroyed when leaving the function 'getPtrToArray'. You must not return a pointer to a local variable.