Mental model
A spreadsheet, an image or a game board is a grid: you think of element (r, c), row r and column
c. Memory has no grid. It is one long row of numbered bytes, as the
array layout lesson showed for a
one-dimensional array, where element i lives at base + i × size.
So every two-dimensional array is a decision about how to flatten the grid. There are two main designs:
- One contiguous block. All
rows × colselements sit in a single block, either row after row (row-major) or column after column (column-major). Finding an element is arithmetic. - An array of rows (jagged). An outer array holds references to separate row arrays. Finding an element means reading a reference first, and the rows can have different lengths.
The lab shows both. In rectangular mode it draws the logical grid on top and the same elements in memory order underneath, with the address of every cell; the current element lights up in both, and an arrow shows how far the read jumped from the previous one.
Row-major and column-major
Take a 3 × 4 matrix of 4-byte integers starting at address 1000, where element (r, c) holds
r·10 + c (the lab uses the same values, so a value tells you its own position).
Row-major stores row 0, then row 1, then row 2:
offset(r, c) = r · cols + c
address(r, c) = base + (r · cols + c) · size
memory: 0 1 2 3 | 10 11 12 13 | 20 21 22 23
address 1000 ... 1016 ... 1032 ... 1044
Column-major stores column 0, then column 1, and so on:
offset(r, c) = c · rows + r
memory: 0 10 20 | 1 11 21 | 2 12 22 | 3 13 23
Neither is more correct. C, C++, C#, NumPy (by default, order='C') and most of the languages you
will meet use row-major. Fortran, MATLAB, R, Julia and many linear-algebra libraries (BLAS and LAPACK
follow Fortran) use column-major; NumPy can create column-major arrays with order='F'. Mixing the
two conventions, for example handing a C array to a Fortran routine, silently transposes the matrix.
More than two dimensions
The rule generalises: in row-major order the last index varies fastest. For a d0 × d1 × d2
array,
offset(i, j, k) = (i · d1 + j) · d2 + k
Each index has a stride, the number of elements you skip when it grows by one: d1·d2 for i,
d2 for j, 1 for k. Column-major reverses it: the first index varies fastest. Libraries such
as NumPy and C++'s std::mdspan store exactly these strides, which is how they describe transposed
views and slices without copying.
Loop order and the cache
Both traversals below read every element once, so both are O(rows × cols):
for r in 0 … rows-1: for c in 0 … cols-1:
for c in 0 … cols-1: for r in 0 … rows-1:
read m[r][c] read m[r][c]
On row-major storage the left loop reads addresses 1000, 1004, 1008, … : each read is the next
element. The right loop reads 1000, 1016, 1032, then jumps back to 1004: every step is a jump of
cols × size bytes (or a jump back to the top of the next column). Run the Row by row and Column
by column presets: same matrix, same reads, same sum; the Contiguous steps and Jumps metrics
flip.
Why it matters: processors move memory into the cache in whole lines, typically 64 bytes. A row-order loop over 4-byte ints uses all 16 values in every line it loads. A column-order loop with a row length of 64 bytes or more touches a different line on every read; if the matrix is larger than the cache, each line may be evicted before the loop comes back for its neighbours. The preset Column order, 64-byte stride shows that case: 8 columns of 8-byte values, so every step moves exactly one line ahead.
Be honest about what the lab shows: it counts address steps, a model of access patterns, not time. How much a swapped loop costs on real hardware depends on the matrix size, the cache sizes, the hardware prefetcher (which handles constant strides well) and the compiler (which sometimes interchanges loops for you). For small matrices that fit in the cache the difference can vanish; for large ones it is often several times. Measure with a profiler or a benchmark harness before rewriting code for it, but write the loop in storage order by default.
The rule of thumb: make the innermost loop walk the index that varies fastest in memory, the last index for row-major data and the first for column-major data.
Jagged arrays
A jagged array is an array whose elements are references to other arrays. Each row is a separate object somewhere on the heap:
rows ──▶ [ref0, ref1, ref2]
│ │ └──▶ [20 21]
│ └──▶ [10]
└──▶ [0 1 2 3]
That buys flexibility and costs indirection:
- Rows can differ in length, including length 0. Triangular tables, adjacency lists and lines of text fit naturally. Run the Jagged rows preset: rows of 4, 1, 3, 0 and 2 elements.
- Rows can be replaced or shared by assigning a reference, without copying elements.
- Every row costs a reference read before its first element (the Row reference reads metric), plus an object header and a separate allocation per row.
- Rows are not adjacent. Within a row, reads are contiguous; between rows the address jumps to wherever the allocator put the next row. The lab's row addresses are illustrative (an allocator could place them anywhere); the point is that nothing promises they are neighbours.
To reach element (r, c) you read rows[r] (one memory access), then index that row. There is no
single formula from (r, c) to an address.
What each language gives you
| Contiguous rectangular array | Jagged array of rows | |
|---|---|---|
| C# | int[,] (rank 2), one block, row-major |
int[][], each row a separate int[] |
| Python | none in the core language; numpy.ndarray (C or F order) |
list of lists (the usual "matrix") |
| Java | none: a "2D array" is always an array of arrays | int[][], also from new int[3][4] |
| C++ | int a[3][4], std::array<std::array<int, 4>, 3>, a flat std::vector<int> with r*cols + c, or std::mdspan over a buffer |
std::vector<std::vector<int>> |
More precisely:
- C# has true multidimensional arrays:
new int[3, 4]is one object whose elements the CLI lays out in row-major order (ECMA-335 requires it; the C# test copies anint[,]byte for byte withBuffer.BlockCopyand gets row-major order).m.Lengthis 12,m.Rankis 2,m.GetLength(1)is 4. A jaggedint[][]is an array ofint[]references;new int[3][]creates only the outer array, and each row needs its ownnew int[n]. The JIT optimises single-dimensional zero-based arrays especially well, so performance-sensitive .NET code often uses jagged arrays or a flatint[]with manualr * cols + cindexing; measure if it matters. Out-of-range indices throwIndexOutOfRangeExceptionper dimension. - Python lists hold references, so a list of lists is jagged by nature, with each row a separate
list object and each element a reference to an
intobject. Thearraymodule stores numbers compactly but is one-dimensional. NumPy'sndarrayis a genuine contiguous block with shape and strides;np.zeros((3, 4))is row-major,np.zeros((3, 4), order='F')column-major, anda.flagstells you which. The listing uses a flat list to show the row-major arithmetic. - Java has only arrays of arrays (JLS chapter 10).
new int[3][4]allocates one outer array and three separateint[4]objects;new int[3][]leaves the rowsnull. Each row is a full object with its own header and length, and the rows need not be adjacent. For a cache-friendly dense matrix, Java code typically uses oneint[rows * cols]with manual indexing, as the listing does. - C++ built-in arrays of arrays are contiguous:
int a[3][4]is 12 ints in a row, row-major, with no per-row overhead (the C++ test checks that inint g[2][3],&g[1][0]is&g[0][0] + 3).std::vector<std::vector<int>>is jagged: each inner vector owns its own heap block. C++23'sstd::mdspanputs a multidimensional view over any contiguous buffer:layout_right(the default) is row-major,layout_leftis column-major,layout_stridetakes arbitrary strides, and C++23 allowsm[r, c]with a multidimensional subscript operator.
Common mistakes
- Swapping the loops on large data: correct results, many more cache misses.
- Mixing conventions: computing
r * rows + cinstead ofr * cols + c, or passing row-major data to a column-major library without transposing. - Out-of-range columns that land inside the block. In a flat buffer,
(0, 5)of a 3 × 4 matrix has offset 5, which is the valid element(1, 1). Nothing fails; you read the wrong element. C#int[,]and Java check each index separately; in C++a[0][5]onint a[3][4]is undefined behaviour even though the memory exists, and a flatstd::vectorwithoperator[]checks nothing. - Aliased rows in Python.
[[0] * 3] * 3creates one row list and three references to it;grid[0][0] = 1changes all three rows. Use[[0] * 3 for _ in range(3)]. The same trap exists in Java withArrays.fill(rows, oneRow). The Python and Java tests check both behaviours. - Forgetting to allocate jagged rows:
new int[3][](C#, Java) gives threenullrows. - Assuming rows of equal length when the input is jagged; loop to each row's own length.
Edge cases
- One row (1 × n) or one column (n × 1): both loop orders walk memory contiguously, because one of the strides never comes into play. The One row preset shows column order with no jumps.
- An empty jagged row: one reference read, no element reads.
- A jagged array with no rows: nothing to read, sum 0.
rows × colsoverflowing a 32-bitintfor very large matrices: compute offsets in 64 bits (long,std::size_t), as the address helpers in the listings do.
The teaching implementation
RowMajor / row_major and ColumnMajor / column_major read a flat row-major buffer with the
same offset formula and differ only in loop order, which is the whole lesson. Jagged / jagged
reads the row reference, then the row. AddressOf / address_of is the address formula; the tests
use it to recompute every address and count the jumps. All four languages run one shared fixture
(visit order, sum, jumps and the last address, from 1 × 1 to 6 × 8 and with empty and uneven jagged
rows) and compare 500 random shapes with plain nested loops.
Worked practice
1. A row-major int matrix (4 bytes per element) with 5 rows and 7 columns starts at address 2000. What is the address of element (3, 4)?
Answer
Offset = 3 · 7 + 4 = 25, address = 2000 + 25 · 4 = 2100.
2. The same matrix is read column by column. How many bytes apart are two consecutive reads within one column, and what happens at the end of a column?
Answer
cols × size = 7 · 4 = 28 bytes. After row 4 of column c (offset 4·7 + c) the next read is row 0 of
column c + 1 (offset c + 1), a jump back of 27 elements = 108 bytes.
3. Give the column-major offset of (i, j, k) in a d0 × d1 × d2 array.
Answer
The first index varies fastest: offset = i + d0 · (j + d1 · k). The strides are 1, d0 and
d0·d1.
4. You store a triangle of distances where row r has r + 1 entries. Which layout would you choose, and how much space does each need for n rows?
Answer
A jagged array stores exactly n(n + 1)/2 values plus n row references and headers. A rectangular n × n array wastes almost half its n² slots. A third option is one flat array of n(n + 1)/2 values with row r starting at offset r(r + 1)/2: contiguous and compact, at the price of a less obvious formula.
Summary
- Memory is linear; a 2D array is either one block (row-major or column-major) or an array of row references (jagged).
- Row-major:
address = base + (r · cols + c) · size; the last index varies fastest. Column-major:c · rows + r; the first index varies fastest. - Loop in storage order. The lab counts contiguous steps and jumps; real costs depend on cache and prefetching and should be measured.
- Jagged arrays allow rows of any length at the cost of one reference read per row and scattered rows.
- C# has both
int[,]andint[][]; Java and Python lists have only arrays of rows; C++ has contiguousT[R][C], jaggedvector<vector<T>>, andstd::mdspanfor views with either layout.