In dynamic allocation of arrays at runtime, when the array is declared before getting the array length, I encountered a behavior that could not explain.
In the following code, the user provides the length of the array, say 5
and then provides five space-separated numbers as input, say 4 3 7 2 1
. By printing length
after the for
loop we see that it changes.
Here is the code.
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int length;
int ar[length];
cout << "Enter the length of array: ";
cin >> length;
cout << "--- length before: " << length << endl;
cout << "Provide " << length << " integer values separated by space and then press Enter." << endl;
for (int i = 0; i<length; i++)
{
cin >> ar[i];
cout << "i: " << i << " - ar[i]: " << ar[i] << endl;
}
cout << "--- length after: " << length << endl;
return 0;
}
And the output with input 4 3 7 2 1
:
Enter the length of array: 5
--- length before: 5
Provide 5 integer values separated by space and then press Enter.
4 3 7 2 1
i: 0 - ar[i]: 4
i: 3 - ar[i]: -1
--- length after: 4
After trying out different inputs, I found that length
is changed to the first input integer, here 4
. The value of i
in the loop also jumps based on the given input.
I know the array has to be declared after cin
but any explanations for the behavior?
6