Input values into an array.

Hey,

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace 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.

Thanks!!
Last edited on
Valid indices for array are from 0 to n-1.

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
Topic archived. No new replies allowed.