Frosty Owl
Frosty Owl

Reputation: 31

c++ 2D array: Each element is given a number but output is a different number

I wrote the code below expecting to get 123456789 when running. However instead I get 124457789 and I can for the life of me figure out why. Why won't my code do what I think it is supposed to do?

If I change the numbers the third and sixth number will still be the same as the fourth and seventh numbers.

#include<iostream>
#include<string>
#include<cmath>

using namespace std;

int main(){

    int matrix[2][2];
    matrix[0][0]=1;
    matrix[0][1]=2;
    matrix[0][2]=3;
    matrix[1][0]=4;
    matrix[1][1]=5;
    matrix[1][2]=6;
    matrix[2][0]=7;
    matrix[2][1]=8;
    matrix[2][2]=9;

    cout<<matrix[0][0];
    cout<<matrix[0][1];
    cout<<matrix[0][2];
    cout<<matrix[1][0];
    cout<<matrix[1][1];
    cout<<matrix[1][2];
    cout<<matrix[2][0];
    cout<<matrix[2][1];
    cout<<matrix[2][2];
}

Upvotes: 3

Views: 302

Answers (2)

WhozCraig
WhozCraig

Reputation: 66194

Your matrix is only indexable from [0][0] through [1][1], as it is a 2x2 declaration. You're indexing to [2][2], and thus this is undefined behavior.

Declare your matrix as matrix[3][3] and try again.

EDIT Loading with 1-9 using a modulo/division loop for kicks.

int matrix[3][3];
for (int i=0;i<9;++i)
    matrix[i/3][i%3] = (i+1);

Stare at that for awhile and see if you understand how it has the same result as you rather large stack of direct assignments. Likewise on the print-side:

for (int i=0;i<9;++i)
    cout << matrix[i/3][i%3];
cout << endl;

Upvotes: 4

Foggzie
Foggzie

Reputation: 9821

should be a 3x3 array, not a 2x2:

int matrix[3][3];

Otherwise, anything indexed with a 2 will cause undefined behavior.

Upvotes: 1

Related Questions