2d array

Hi All,

This is from a problem published on heakerearth.com

We need to create a 2 dimensional array and fill it.

for the creating of the array I've used:
1
2
3
    for (int i = 0; i<= n;i++){
        A[i] = new int [m];
    }


when I let the program create a 2 x 2 array there is no problem Neither with a 2 x 3 or a 4 x 4. When I let the program create a 3 x 3 or a 3 x 2 array the filling breaks at value [i][j] [2][0]. So I think there must be something wrong there.

For testing I added a cout line in the creating part. Then I can create and fill a 3 x 3 array, but not the 3 x 2. I can still create and fill a 4 x 4 array.

1
2
3
4
    for (int i = 0; i<= n;i++){
        cout << i;
        A[i] = new int [m];
    }


Then I removed the cout << i; and changed the cout lines that asks for the input.

1
2
3
4
5
    //not working code....
    cout <<"give amount of rows \n";
    cin >> N;
    cout <<"\ngive amount of columns \n";
    cin >> M;


Removed the \n at the end of the line because I do think they have got something to do with it.

1
2
3
4
5
    /Working code....
    cout <<"give amount of rows ";
    cin >> N;
    cout <<"\ngive amount of columns ";
    cin >> M;


I'm missing some vital information about streams and I do not know what it is. Any tips, suggested reading (youtube) would be very welcome.

thank you


And then The whole code as it is working....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  int main() {
    
    //N, n, i = Rows, M = Columns
    int N, M, n, m;
    cout <<"give amount of rows ";
    cin >> N;
    cout <<"\ngive amount of columns ";
    cin >> M;
    n = N - 1;
    m = M - 1;
    
    int** A = new int*[n];

    for (int i = 0; i<= n;i++){
        A[i] = new int [m];
    }

    for(int i = 0; i <= n; i++){
        for (int j = 0; j <= m; j++ ){
            cout << "value [" << i << "][" << j <<"]: ";
            cin >> A[i][j];
        }
    }
    for (int i = 0 ; i <= n; i++){
        for (int j = m; j >= 0 ; j--){
            cout << A[i][j] << " ";
        }
        cout << '\n';
    }
    
    return 0;
}
Last edited on
this is all weird.

if you want 10 columns, n = 10.
you get to it from 0- 9, but that is still 10 things (count them!): {0,1,2,3,4,5,6,7,8,9}

so your subtraction of 1 and use of <= combined are causing havoc with the code.

try
cin >> n
cin >> m
a = new int[n];
for()
a[i] = new int[m];

without all the -1 and <= stuff and it will work better

Last edited on
Topic archived. No new replies allowed.