Row Major Ordering

Main memory (i.e., RAM) occupies a linear address space, which just means that it can be treated as a huge, one-dimensional array. That means that if our program has a two-dimensional array (or higher) that the compiler must somehow map the two dimensions of the array into one the one dimension of main memory for storage. There are two ways to do this: row major order and column major order. Both are illustrated below but row major is by far the most commonly used today (hence, the name of this section).

Mapping a two-dimensional array to linear addressing Assume a 4x3 array (e.g., T a[4][3]; where T is some type and a is the name of the array). The array may be stored in main memory in one of two ways: row major (data is entered row by row) or column major (data is entered column by column).

As row major is used more than is column major, the example below is based on row major storage. In this example, nrows = 4, ncols = 3 (the size of the array). Suppose that the program needs to access the element a[i][j] (where i is the row = 2 and j is the column = 1). This element is highlighted in yellow. The calculation is as follows:

RM_address = i * ncols + j = 2 * 3 + 1 = 7
so a[i][j] = RM[i * ncols + j]
a[2][1] = RM[7]

Notice that nrows never figures into the calculation, so that information is not required in either the function call nor the parameter. This "trick" can be extended to higher dimensions and is useful if you want to create a function that takes a multi-dimensional array argument but make the function definition independent of the array size (but the number of rows must be passed in as a separate parameter).

Example

#include <iostream>
using namespace std;

void print(char* array, int i, int j, int ncols)
{
	cout << array[i * ncols + j] << endl;
}

int main()
{
	char	a1[4][3] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L' };
	char	a2[3][2] = { 'u', 'v', 'w', 'x', 'y', 'z' };

	print((char *)a1, 2, 1, 3);
	print((char *)a2, 1, 0, 2);

	return 0;
}

The function

void print(char* array, int i, int j, int ncols)

is a more general replacement for (in this example) two functions:

void print(char array[][3], int i, int j)
void print(char array[][2], int i, int j)

Furthermore, the general function will continue to work when additional arrays with different dimension sizes are added to the program. The alternative requires a new function tailored to each array size.