In C, when you define an array like:
int a[2][3];
DOES C consider that as 2 arrays of 3 ints, or is it 3 arrays of 2 ints?
I’ll tell you the answer soon .
.
.
.
.
But you have to guess first.
.
.
.
.
.
.
Ok.
IT IS TWO arrays of THREE ints. You read it from left to right.
So, if we define:
int a[2][3] = {
{ 3, 5, 7 },
{ 9, 1, 0 }
} ;
We know that’s right because if we tried to do it any other way, (like
int a[2][3] = {
{ 9, 9 },
{ 9, 0 },
{ 2, 2 }
} ;
) we’d get something like “error: too many initializers” from the C compiler. That’s because this HAS TO BE an array of TWO arrays of THREE ints each.
ok ok but what about row major vs column major?
Row major vs column major really has to do with whether you think of a matrix as a collection of row vectors (“row major”), or if you prefer to think of a matrix as a collection of COLUMN VECTORS (aka “column major”).
Let’s start with column major.
interpreting the matrix as column major
So, don’t forget, we had:
int a[2][3] = {
{ 3, 5, 7 },
{ 9, 1, 0 }
} ;
If we’re thinking COLUMN MAJOR, then we will understand this to be 2 COLUMN VECTORS, WITH 3 ENTRIES EACH.
SO, we’d visualize the array as:
interpreting the matrix as ROW MAJOR
If we were to think of that same matrix:
int a[2][3] = {
{ 3, 5, 7 },
{ 9, 1, 0 }
} ;
If we’re thinking ROW MAJOR, then we will understand this to be 2 __ROW__ VECTORS, WITH 3 ENTRIES EACH.
So we’d visualize:
dealing with both types
Ok so notice the COLUMN MAJOR matrix was like:
and the ROW MAJOR was like:
So, let’s notice a few things that are interesting.
Notice that the original data was:
int a[2][3] = {
{ 3, 5, 7 },
{ 9, 1, 0 }
} ;
Now, notice this. The COLUMN MAJOR version has the values go inside it IN ORDER, DOWN THE COLUMNS.
The ROW MAJOR version has the values go inside it, IN ORDER, DOWN THE ROWS.
accessing and modifying values of row major and column major mats
If you’re accessing the COLUMN MAJOR matrix, you’d write something like:
a[1][2] = 99; // set a[COL=1][ROW=2] TO 99;
// In the COLUMN MAJOR MATRIX,
// the specification of the COLUMN to hit
// comes first.
If you’re accessing the ROW MAJOR matrix, you’d write something like:
a[1][2] = 2000; // set a[ROW=1][COL=2] TO 2000;
// In the ROW MAJOR matrix,
// specification of the ROW to hit
// comes first.
BUT NOTICE, in the two green examples, we are HITTING THE SAME ENTRY IN THE MATRIX.
accessing a 1D array as row major, or column major
SAY you stored the matrix values in a 1D array.
int m[6] = {3,5,7,9,1,0};
Results in something like:
in C memory.
If you want to treat this 1D array as a COLUMN MAJOR matrix, you’d access it like this:
A[col][row] = A[row + col*NUMROWS];
If you want to treat this 1D array as a ROW MAJOR matrix, you’d access it like this:
A[row][col] = A[col + row*NUMCOLS];