How to correctly fill 2D array in C++ using user input?

1

I am trying to make a 2D array in C++ and fill it with user input, but once I start typing in values the program just stops giving me "Process finished with exit code -1073741819 (0xC0000005)"

double ** array = new double*[col];
for( i=0;i< col; i++){
    array[i] = new double [row];
}


for(i1=0;i1<row;i1++){
    for(j=0;j<col;j++){
        cin>> n;
        array[i1][j] = n;
    }
}

for(i1=0;i1<row;i1++){
    cout<<" "<<endl;
    for(j=0;j<col;j++){
        cout<< array[i1][j];
        cout<<" ";

    }
}

Any ideas how to solve this?

c++
arrays

1 Answer

1

Let's just ignore memory allocation, for simplicity's sake. Your code should look like this:

int val;
  int max = 16;
  int arr[max][max];

  for(int i = 0; i < max; i++){
      for(int j = 0; j < max; j++){
        cin >> val;
        arr[j][i] = val;
      }
  }

Note how in a 2D array, it goes array[ROW][COLUMN]. Because of this, you want to have a double for loop, with column++ going after a whole for loop of row++. It looks like you've got array[COLUMN][ROW], which is why it's not working properly.

answered on Stack Overflow Nov 2, 2018 by Little Boy Blue • edited Nov 2, 2018 by Little Boy Blue

User contributions licensed under CC BY-SA 3.0