Lovecraft
Lovecraft

Reputation: 101

A simple matrix in C

I can't figure out why the following code produces 43213987.

#include <stdio.h>

int main(){

    int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    for(int i=0; i<3; i++)
        for(int j=3; j>=0; j--)
            if(i%2==0)
                printf("%d", a[i][j]);

    return 0;
}

How the second 3 printed on screen is accessed? How a[2][3] can be legal?

Upvotes: 0

Views: 95

Answers (1)

msc
msc

Reputation: 34738

How a[2][3] can be legal?

No, it is not legal. It is undefined behavior because out of array bound.

c99 draft standard section Annex J.2 J.2 Undefined behavior includes the follow point:

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

Upvotes: 1

Related Questions