Row-major order
From Wikipedia, the free encyclopedia
In computing, row-major order and column-major order describe methods for storing multidimensional arrays in linear memory. Array layout is critical for correctly passing arrays between programs written in different languages. It is also important for performance when traversing an array because accessing array elements that are contiguous in memory is usually faster than accessing elements which are not, due to caching.
[edit] 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 exceptions of Fortran and MATLAB.
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 2 3 4 5 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:
Where NUMCOLS is the number of columns in the array.
[edit] 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 languages Fortran and MATLAB use column-major ordering. The array
1 2 3 4 5 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:
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.