I'm trying to input some values into an array. The array lenght is determined by an integer 'n' the user inputs. I haven't succeed in storing the values of each positition into the array using a while loop and a new variable 'i' to get 'n' values.
#include <iostream>
usingnamespace std;
int main() {
int n, i(0);
cin >> n;
int array [n];
while (i < n) {
int a;
cin >> a;
array [i] = a;
i = i + 1;
}
cout << array [n] << endl;
}
I don't know what I'm doing wrong, because the program prints completely different values to the ones from the input.
When you try to output array[n] you are accessing memory that is off of the end of the array - so you basically end up accessing a (possibly) unitialised area of memory that contains a random value,
If you change line 21 to cout << array[n-1] << endl; then you should get the behaviour you expect