I have a function that fills up a dynamic array by first putting values into a vector.
void fillArray(int*& arr) {
vector<int> temp;
for(int i = 0; i < 10; i++) {
temp.push_back(i);
}
arr = &temp[0];
}
int main() {
int* arr;
fillArray(arr);
for(int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9
Based on this answer, the code I'm using only creates a pointer to the vector's internal array - but said vector is destroyed after leaving the scope of the function. Why is it then that printing the array after the fact gives me the correct output?
According to the answers of this question, I should indeed be getting errors. So why does this work? [Runnable version]