Row-major order & Column-major order

In computing, row-major order and column-major order describe methods for storing multidimensional arrays in linear memory. Array order is critical for correctly passing arrays between programs written in different languages. It is also important for performance when traversing an array because accessing an array in the same order the elements appear in memory (memory coherency) is generally faster than accessing the elements out of order.

Row-major order
In row-major storage, a multidimensional array in linear memory is accessed such that rows are stored one after the other. It is the approach used by the C programming language as well as many other languages, with the notable exception of Fortran. When using row-major order, the difference between addresses of array cells in increasing rows is larger than addresses of cells in increasing columns. For example, consider this 2×3 array:
1 4 2 5 3 6

Declaring this array in C as
int A[2][3] = { {1, 2, 3}, {4, 5, 6} };

would find the array laid-out in linear memory as:
1 2 3 4 5 6

The difference in offset from one column to the next is 1 and from one row to the next is 3. The linear offset from the beginning of the array to any given element A[row] [column] can then be computed as: offset = row*NUMCOLS + column Where NUMCOLS is the number of columns in the array.

Column-major order
Column-major order is a similar method of flattening arrays onto linear memory, but the columns are listed in sequence. The programming language Fortran uses column-major ordering. The array

1 4

2 5

3 6

if stored in memory with column-major order would look like the following:
1 4 2 5 3 6

With columns listed first. The memory offset could then be computed as: offset = row + column*NUMROWS where NUMROWS represents the number of rows in the array—in this case, 2. It is possible to generalize both of these concepts to arrays with greater than two dimensions. For higher dimension arrays, the ordering determines which dimension of the array is listed off first. Any of the dimensions could be listed first, just the same way that a two-dimensional array could be listed column-first or row-first. The difference in offset between listings of that dimension would then be determined by a product of other dimensions. It is uncommon to have any variation except ordering dimensions first to last or last to first--equating to row-major and column-major respectively. Treating a row-major array as a column-major array is the same as transposing it.

Sign up to vote on this title
UsefulNot useful