Home > database >  Why are row and column indeces reversed?
Why are row and column indeces reversed?

Time:03-12

int numberarray[3][5] = {
    {00, 01, 02, 03, 04},
    {10, 11, 12, 13, 14},
    {20, 21, 22, 23, 24},
};

why is number[3][5] considered as three lists of 5 integers?

If int is a number, and int[3] means a list of 3 numbers, shouldn't int[3][5] be five int[3]?

CodePudding user response:

This declaration

int numberarray[3][5];

may be rewritten like

int ( numberarray[3] )[5];

If you will introduce this typedef

typedef int T[5];

then the above declaration will look like

T numbers[3];

So you have an array with 3 elements of the type int[5].

In general of you have an array like

T a[N1];

then this declaration

T a[N2][N1];

declares an array of N2 elements of the type T[N1].

This declaration

T a[N3][N2][N1];

declares and array with N3 elements of the type int[N2][N1]. And so on.

Also pay attention to that in this declaration

int numberarray[3][5] = {
    {00, 01, 02, 03, 04},
    {10, 11, 12, 13, 14},
    {20, 21, 22, 23, 24},
};

each braced initializer in fact initializes a one-dimensional array with 5 elements. The above declaration can be rewritten like

int numberarray[][5] = {
    {00, 01, 02, 03, 04},
    {10, 11, 12, 13, 14},
    {20, 21, 22, 23, 24},
};

So within the outer braces there are three braced initializers that can be used to initialize 3 one-dimensional arrays with 5 elements.

So you have int numberarray[3][5].

CodePudding user response:

why is number[3][5] considered as three lists of 5 integers?

Because of language details. There are arrays:

type identifier[amount];

Languagewise, that's all there is to it. You can certainly make an array of such a type:

typedef type[dim] moar;

... and you would have another dimension of whatever you'd like to iterate over.

"reversed" is just an idea and it depends on where you come from. You can say it's reversed and you would not be wrong but it depends on context. I'm used to row-major-order so for me this feels natural. There is no "correct" way until you put it in some context.

CodePudding user response:

In C/C the declarations are parsed outwards, starting from the variable name:

    arr        // `arr` is...
    arr[3]     // an array of size 3 of...
    arr[3][5]  // arrays of size 5 of...
int arr[3][5]  // int
  • Related