I am new to C++. Below is code to input and display an array -- a simple thing to understand how things work.
int main() {
int N, i;
int A[N];
cin >> N;
for (i = 0; i < N; i++) {
cin >> A[i];
}
for (i = 0; i < N; i++) {
cout << A[i];
}
return 0;
}
The input is:
4
1 2 3 4
and output is:
12
I have corrected my code to:
int N, i;
cin >> N;
int A[N];
This correctly displays the array.
What exactly happened? Should N have a value before initializing A[N]? But then why didn't my initial code work? Is this something to do with Hierarchy? If so, how can I get my priorities right?
If N is initialized as a large value, N has an input of specific number next, if so how come even if N=9, the output remains same: 12?