Unexpected array behaviour

I want to have a matrix filled with zeros and then be able to change specific elements of that matrix to either 1 or 2.

In the code below I expect the matrix to come out like:
0020
0001
0002
0000

However it turns out it is
0020
0001
1002
2000

Could someone please explain this behaviour and help me achieve what I want?

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
#include <iostream>
using namespace std;

int main() {
	int n = 3;
	int array[n][n];

	for (int i = 0 ; i <=n ; i++) {
		for (int j = 0 ; j <=n ; j++) {
			array[i][j] = 0;
			cout << array[i][j];
		}//for
		cout << endl;
	}//for
	cout << "===============================================================" << endl;
	
	array[0][2] = 2;
	array[1][3] = 1;
	array[2][3] = 2;
	
	for (int i = 0 ; i <=n ; i++) {
		for (int j = 0 ; j <=n ; j++) {
			cout << array[i][j];
		}//for
		cout << endl;
	}//for	
}//main 
You have allocated a 3x3 array but you are using it as if it were a 4x4 array.

If you want a 4x4 array you should change n to 4, and if you don't want to rely on non-standard compiler extensions you also need to make it a constant.

 
const int n = 4;


You also need to change i <= n to i < n (same for j).
Last edited on
In C, indices go from 0 to one less than the size. And if you want the size to be 4 by 4, then N must be 4, not 3. And N should be const (in standard C++).

BTW, those //for, //main, etc comments are just clutter.
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
#include <iostream>
#include <string>
using namespace std;

int main() {
    const int N = 4;
    int array[N][N] = {{0}};

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            cout << array[i][j];
        cout << '\n';
    }

    cout << string(40, '=') << '\n';
    
    array[0][2] = 2;
    array[1][3] = 1;
    array[2][3] = 2;
    
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            cout << array[i][j];
        cout << '\n';
    }
}

Cheers to you both.
I guess I was confused between a size 4x4 array having indices 0 through 3.
Last edited on
Topic archived. No new replies allowed.