M05 · Arrays

Multidimensional and Jagged Arrays

A matrix has rows and columns, but memory is one long line of bytes. Every language has to flatten the grid somehow: one contiguous block in row-major or column-major order, or an array of separate rows. The choice decides the address formula, which loop order is cache friendly, and whether rows can have different lengths.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M05 Arrays · 5 of 5 lessons available

You will be able to

  • Compute the offset and byte address of element (r, c) in a row-major and in a column-major block, and generalise the formula to k dimensions.
  • Predict the address step between consecutive reads for row-order and column-order loops, and explain why one uses cache lines fully and the other may not.
  • Tell a rectangular (contiguous) multidimensional array from a jagged array of row references, and state what each costs.
  • Name what C#, Python, Java and C++ give you for two-dimensional data, including C# int[,] versus int[][] and C++ std::mdspan.
  • Avoid the classic pitfalls: aliased rows in Python, out-of-range column indices that land inside the block, and swapped loop orders.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M04 Built-in Collections — The collections every language ships, what each operation costs, and how to choose one.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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 × cols elements 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 an int[,] byte for byte with Buffer.BlockCopy and gets row-major order). m.Length is 12, m.Rank is 2, m.GetLength(1) is 4. A jagged int[][] is an array of int[] references; new int[3][] creates only the outer array, and each row needs its own new int[n]. The JIT optimises single-dimensional zero-based arrays especially well, so performance-sensitive .NET code often uses jagged arrays or a flat int[] with manual r * cols + c indexing; measure if it matters. Out-of-range indices throw IndexOutOfRangeException per 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 int object. The array module stores numbers compactly but is one-dimensional. NumPy's ndarray is a genuine contiguous block with shape and strides; np.zeros((3, 4)) is row-major, np.zeros((3, 4), order='F') column-major, and a.flags tells 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 separate int[4] objects; new int[3][] leaves the rows null. 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 one int[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 in int 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's std::mdspan puts a multidimensional view over any contiguous buffer: layout_right (the default) is row-major, layout_left is column-major, layout_stride takes arbitrary strides, and C++23 allows m[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 + c instead of r * 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] on int a[3][4] is undefined behaviour even though the memory exists, and a flat std::vector with operator[] checks nothing.
  • Aliased rows in Python. [[0] * 3] * 3 creates one row list and three references to it; grid[0][0] = 1 changes all three rows. Use [[0] * 3 for _ in range(3)]. The same trap exists in Java with Arrays.fill(rows, oneRow). The Python and Java tests check both behaviours.
  • Forgetting to allocate jagged rows: new int[3][] (C#, Java) gives three null rows.
  • 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 × cols overflowing a 32-bit int for 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[,] and int[][]; Java and Python lists have only arrays of rows; C++ has contiguous T[R][C], jagged vector<vector<T>>, and std::mdspan for views with either layout.

Full implementation

Row-order, column-order and jagged traversals in four languages, each checked against one shared fixture (visit order, sum, number of address jumps and the last address for 1 × 1 up to 6 × 8 matrices, single rows and columns, empty and uneven jagged rows), and 500 random shapes compared with plain nested loops; C# also checks that an int[,] copies out in row-major order, C++ that int[2][3] is one contiguous block.

namespace Bekadan.Dsa.Examples.Arrays;
 
/// <summary>
/// Reading a two-dimensional array in row order, in column order, and as a
/// jagged array of rows. A rectangular matrix is stored row-major in one block
/// (as <c>int[,]</c> is): element (r, c) sits at offset r * cols + c. Every
/// traversal reads each element once: O(rows * cols) time, O(1) extra space
/// besides the returned list.
/// </summary>
public static class MatrixTraversal
{
    /// <summary>Row order over row-major storage: consecutive reads are adjacent in memory.</summary>
    public static List<int> RowMajor(ReadOnlySpan<int> flat, int rows, int cols)
    {
        var order = new List<int>(rows * cols);
        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)
            {
                int offset = r * cols + c;
                order.Add(flat[offset]);
            }
        }
        return order;
    }
 
    /// <summary>Column order over the same row-major storage: each read jumps cols elements ahead.</summary>
    public static List<int> ColumnMajor(ReadOnlySpan<int> flat, int rows, int cols)
    {
        var order = new List<int>(rows * cols);
        for (int c = 0; c < cols; c++)
        {
            for (int r = 0; r < rows; r++)
            {
                int offset = r * cols + c; // same formula, different loop order
                order.Add(flat[offset]);
            }
        }
        return order;
    }
 
    /// <summary>A jagged array: each rows[r] is a reference to its own array, of any length.</summary>
    public static List<int> Jagged(int[][] rows)
    {
        var order = new List<int>();
        for (int r = 0; r < rows.Length; r++)
        {
            int[] row = rows[r]; // read the reference first
            for (int c = 0; c < row.Length; c++)
            {
                order.Add(row[c]);
            }
        }
        return order;
    }
 
    /// <summary>Byte address of element (r, c) in a row-major block starting at baseAddress.</summary>
    public static long AddressOf(long baseAddress, int cols, int elementSize, int r, int c) =>
        baseAddress + (long)(r * cols + c) * elementSize;
 
    /// <summary>
    /// Copies an int[,] into a flat buffer byte for byte. The result is in row-major
    /// order because that is how the runtime lays out a rectangular array.
    /// </summary>
    public static int[] ToRowMajorBuffer(int[,] matrix)
    {
        var flat = new int[matrix.Length];
        Buffer.BlockCopy(matrix, 0, flat, 0, matrix.Length * sizeof(int));
        return flat;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Arrays/MatrixTraversal.cs

"""Reading a two-dimensional array in row order, in column order, and as a
jagged list of rows.
 
Core Python has no rectangular 2D array: a "matrix" is a list of row lists,
each row a separate object. To show the address arithmetic of a real
rectangular array, the first two functions read a flat list in row-major
order, where element (r, c) sits at offset r * cols + c. Every traversal reads
each element once: O(rows * cols) time, O(1) extra space besides the result.
"""
 
from collections.abc import Sequence
 
 
def row_major(flat: Sequence[int], rows: int, cols: int) -> list[int]:
    """Row order over row-major storage: consecutive reads are adjacent."""
    order: list[int] = []
    for r in range(rows):
        for c in range(cols):
            offset = r * cols + c
            order.append(flat[offset])
    return order
 
 
def column_major(flat: Sequence[int], rows: int, cols: int) -> list[int]:
    """Column order over the same row-major storage: each read jumps cols elements."""
    order: list[int] = []
    for c in range(cols):
        for r in range(rows):
            offset = r * cols + c  # same formula, different loop order
            order.append(flat[offset])
    return order
 
 
def jagged(rows: Sequence[Sequence[int]]) -> list[int]:
    """A list of rows: each rows[r] is a reference to its own list, of any length."""
    order: list[int] = []
    for r in range(len(rows)):
        row = rows[r]  # read the reference first
        for c in range(len(row)):
            order.append(row[c])
    return order
 
 
def address_of(base: int, cols: int, element_size: int, r: int, c: int) -> int:
    """Byte address of element (r, c) in a row-major block starting at base."""
    return base + (r * cols + c) * element_size

Tested on CPython 3.14.0 · examples/python/dsa_examples/matrix_traversal.py

package dev.bekadan.dsa.arrays;
 
/**
 * Reading a two-dimensional array in row order, in column order, and as a
 * jagged array of rows. Java has no rectangular array type: {@code int[][]}
 * is an array of references to separate row arrays. To show the address
 * arithmetic of a rectangular block, the first two methods read a flat
 * row-major buffer, where element (r, c) sits at offset r * cols + c. Every
 * traversal reads each element once: O(rows * cols) time, O(1) extra space
 * besides the result.
 */
public final class MatrixTraversal {
    private MatrixTraversal() {
    }
 
    /** Row order over row-major storage: consecutive reads are adjacent in memory. */
    public static int[] rowMajor(int[] flat, int rows, int cols) {
        int[] order = new int[rows * cols];
        int k = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                int offset = r * cols + c;
                order[k++] = flat[offset];
            }
        }
        return order;
    }
 
    /** Column order over the same row-major storage: each read jumps cols elements ahead. */
    public static int[] columnMajor(int[] flat, int rows, int cols) {
        int[] order = new int[rows * cols];
        int k = 0;
        for (int c = 0; c < cols; c++) {
            for (int r = 0; r < rows; r++) {
                int offset = r * cols + c; // same formula, different loop order
                order[k++] = flat[offset];
            }
        }
        return order;
    }
 
    /** An array of arrays: each rows[r] is a reference to its own array, of any length. */
    public static int[] jagged(int[][] rows) {
        int total = 0;
        for (int[] row : rows) {
            total += row.length;
        }
        int[] order = new int[total];
        int k = 0;
        for (int r = 0; r < rows.length; r++) {
            int[] row = rows[r]; // read the reference first
            for (int c = 0; c < row.length; c++) {
                order[k++] = row[c];
            }
        }
        return order;
    }
 
    /** Byte address of element (r, c) in a row-major block starting at base. */
    public static long addressOf(long base, int cols, int elementSize, int r, int c) {
        return base + (long) (r * cols + c) * elementSize;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/arrays/MatrixTraversal.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <span>
#include <vector>
 
namespace bekadan::dsa {
 
// Reading a two-dimensional array in row order, in column order, and as a
// jagged vector of rows. A rectangular matrix is stored row-major in one block
// (as int[R][C] is): element (r, c) sits at offset r * cols + c. Every
// traversal reads each element once: O(rows * cols) time, O(1) extra space
// besides the result.
 
// Row order over row-major storage: consecutive reads are adjacent in memory.
inline std::vector<int> row_major(std::span<const int> flat, std::size_t rows, std::size_t cols) {
    std::vector<int> order;
    order.reserve(rows * cols);
    for (std::size_t r = 0; r < rows; ++r) {
        for (std::size_t c = 0; c < cols; ++c) {
            const std::size_t offset = r * cols + c;
            order.push_back(flat[offset]);
        }
    }
    return order;
}
 
// Column order over the same row-major storage: each read jumps cols elements ahead.
inline std::vector<int> column_major(std::span<const int> flat, std::size_t rows, std::size_t cols) {
    std::vector<int> order;
    order.reserve(rows * cols);
    for (std::size_t c = 0; c < cols; ++c) {
        for (std::size_t r = 0; r < rows; ++r) {
            const std::size_t offset = r * cols + c;  // same formula, different loop order
            order.push_back(flat[offset]);
        }
    }
    return order;
}
 
// A vector of vectors: each row owns a separate heap block, of any length.
inline std::vector<int> jagged(const std::vector<std::vector<int>>& rows) {
    std::vector<int> order;
    for (std::size_t r = 0; r < rows.size(); ++r) {
        const std::vector<int>& row = rows[r];  // find the row block first
        for (std::size_t c = 0; c < row.size(); ++c) {
            order.push_back(row[c]);
        }
    }
    return order;
}
 
// Byte address of element (r, c) in a row-major block starting at base.
constexpr std::uint64_t address_of(std::uint64_t base, std::size_t cols, std::size_t element_size, std::size_t r, std::size_t c) {
    return base + (r * cols + c) * element_size;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/matrix_traversal.hpp

References