Row-major Order - Row-major 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 and the statistical modelling language WinBUGS.

For example, consider this 2×3 array:

 \begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \end{bmatrix}

An array declared in C as

int A = { {1, 2, 3}, {4, 5, 6} };

would be laid out contiguously in linear memory as:

1 2 3 4 5 6

To traverse this array in the order in which it is laid out in memory, one would use the following nested loop:

for (i = 0; i < 2; i++) for (j = 0; j < 3; j++) printf("%d\n", A);

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 can then be computed as:

offset = row*NUMCOLS + column

where NUMCOLS is the number of columns in the array.

The above formula only works when using the C convention of labeling the first element 0. In other words, row 1, column 2 in matrix A, would be represented as A.

Note that this technique generalizes, so a 2×3×4 array looks like:

int A = {{{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}, {{13,14,15,16}, {17,18,19,20}, {21,22,23,24}}};

and the array would be laid out in linear memory as:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Read more about this topic:  Row-major Order

Famous quotes containing the word order:

    The earlier works of a man of genius are always preferred to the newer ones, in order to prove that he is going down instead of up.
    Victor Hugo (1802–1885)