2

with the following code:

#include <iostream>
#define M 3
#define N 5
using namespace std;
int n;
int m;
int my_array[N][M];
void print_a(){
    cout << "array---------------------------------" << endl;
    for (int i = 0; i < m; i++){
        for (int j = 0; j < n; j++){
            cout << my_array[i][j] << " ";
        }
        cout << endl;
    }
}
int main() {
    n = N;
    m = M;
    int j = n - 1;
    for (int i = 0; i < m; i++){
        my_array[i][j] = i + j;
        print_a(); 
    }
    return 0;
}

array---------------------------------
0 0 0 0 4
0 4 0 0 0
0 0 0 0 0
array---------------------------------
0 0 0 0 4
0 4 0 0 5
0 5 0 0 0
array---------------------------------
0 0 0 0 4
0 4 0 0 5
0 5 0 0 6

tow cells in the double array are changed. I know that double array is also single array. so, even the col and row are exchanged. there should not be two cells are changed. It's Why?

user154317
  • 23
  • 4
  • You declare the array with N rows and M columns, but then you fill the array with a loop that goes over M rows and accesses column N-1 – M.M Oct 19 '16 at 05:36
  • You have an array of arrays, and when you fill the values you go out of bounds of the nested array. Going out of bounds leads to *undefined behavior*. – Some programmer dude Oct 19 '16 at 05:38

1 Answers1

1

Swap n by m in your print function.

#include <iostream>
#define M 3
#define N 5
using namespace std;
int n;
int m;
int my_array[N][M];
void print_a(){
    cout << "array---------------------------------" << endl;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < m; j++){
            cout << my_array[i][j] << " ";
        }
        cout << endl;
    }
}
int main() {
    n = N;
    m = M;
    int j = n - 1;
    for (int i = 0; i < m; i++){
        my_array[i][j] = i + j;
        print_a(); 
    }
    return 0;
}

it works.

array---------------------------------
0 0 0 
0 4 0 
0 0 0 
0 0 0 
0 0 0 
array---------------------------------
0 0 0 
0 4 0 
0 5 0 
0 0 0 
0 0 0 
array---------------------------------
0 0 0 
0 4 0 
0 5 0 
0 6 0 
0 0 0

Problem in your code: The number in last column is actually next row's value(second col). This is due to the cpp layout of 2D arrays on your machine. link

Community
  • 1
  • 1
v78
  • 2,803
  • 21
  • 44