I have a function that is returning a pointer to an array. If I try to access the returned pointer with something like array[5] it returns the correct value but if i try to loop over it then it returns random numbers. Why does it return different values when I loop over it but returns the correct ones when I specify the index?
int main()
{
int *array = returnArray();
for (size_t i = 0; i < 10; ++i)
{
cout << array[i] << endl;
}
return -1;
}
int *returnArray()
{
int array2[10];
int *ptr2;
for (size_t i = 0; i < 10; ++i)
{
array2[i] = i;
}
ptr2 = array2;
return ptr2;
}