3

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];
}

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

2 Comments

So when I declare, it starts counting at 1 and but when I actually use it it starts counting at 0? Thanks, it works now :D
@Einherjer Arrays are 0-index-based in C/C++. Get used to that. The size of a dimension is a positive number, but the indexing always starts at zero and runs up to (n-1), where n is the declared dimension size.
1

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

int matrix[3][3];

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.