Multidimensional Arrays
Memory is one long line of addresses, so a grid has to be flattened before it can be stored. The rule used for that, row-major or column-major, decides how an index becomes an address and which loop order runs fast.
Flattening the Grid
- Pick the cell: row r, column c
- Skip r full rows: r × cols slots
- Step c more slots into that row
- Read flat index r × cols + c
Multidimensional arrays are arrays indexed by two or more numbers: a 2D array has rows and columns, a 3D array adds a depth. The hardware has no rows or columns. RAM is a single sequence of addresses, so the grid is laid out in one run and an index formula finds each cell.
The usual rule is row-major order: row 0 first, then row 1, and so on. Each row takes cols slots, so the cell at row r, column c lands at flat index r × cols + c, and its address is base + (r × cols + c) × size, where size is the bytes per element.
That is one multiply and one add, so reading any cell is O(1), the same as a one-dimensional array. The formula uses the number of columns and never the number of rows. That is why C lets you leave out the first size of an array parameter, int f(int a[][4]), but never the second.
The formula also runs backwards. A flat index i belongs to row i / cols and column i % cols (integer division). That trick turns a grid into one sorted list in Search a 2D Matrix, where a single binary search runs over all rows × cols cells.
- Rows and columns are a convention; memory is one line
- The row count is only needed for the bounds check, not the address
- Index i maps back to (i / cols, i % cols)
One Block or an Array of Arrays
Two different structures hide behind the same grid[i][j] syntax. A true multidimensional array is one block: int grid[3][4] in C is 12 integers in a row, and the compiler applies the formula above.
An array of arrays is a one-dimensional array of pointers, each pointing at a row stored somewhere else. That is what new int[3][4] builds in Java and what a Python list of lists is. Reading grid[i][j] costs two memory reads: first the row pointer, then the element.
Because each row is its own object, rows can have different lengths. That is a jagged array, useful for a triangle such as Pascal's, where row i holds i + 1 numbers and no space is wasted. The cost is that grid[i].length must be read per row, never assumed.
For heavy number work in Java, the usual fix is one flat int[rows * cols] indexed by hand with r * cols + c. In Python the same reason is why NumPy exists: a NumPy 2D array is one buffer, while a list of lists is a table of pointers to separate objects.
| One contiguous block | Array of arrays | |
|---|---|---|
| Where | C int g[3][4], C++, NumPy | Java new int[3][4], Python list of lists |
| Memory reads per access | One | Two: row pointer, then element |
| Allocations | One | One per row, plus the pointer table |
| Row lengths | All equal | May differ (jagged) |
| Rows next to each other | Always | Not guaranteed |
- Python trap:
[[0] * cols] * rowsrepeats one row object, so writinggrid[0][0]changes every row; use[[0] * cols for _ in range(rows)] - A jagged row may be empty; code that reads
grid[i][0]must check the length first - C# has both:
int[,]is one block,int[][]is jagged
Loop Order Decides the Speed
The CPU does not fetch one number at a time. It loads a cache line, usually 64 bytes, which is sixteen 4-byte integers, and it prefetches the next lines when it sees a steady forward pattern.
In row-major storage the cells of one row are neighbours. Looping with rows outside and columns inside walks straight through memory: one cache line serves sixteen reads and the prefetcher keeps ahead.
Swap the loops and each read jumps cols × size bytes. On a large grid every read can land on a new cache line, so identical work can run several times slower. Both orders are still O(rows × cols); big-O counts steps, not cache misses.
Naive matrix multiplication suffers from exactly this, because its inner loop walks one matrix down a column. The standard fixes are transposing that matrix first, so both are read along rows, or tiling, which works on small blocks that fit in cache.
- Row-major data: rows in the outer loop, columns in the inner loop
- A compiler may swap the loops for you only when it can prove it is safe
- On a 2 × 3 grid the good order reads slots 0, 1, 2, 3, 4, 5; the bad order reads 0, 3, 1, 4, 2, 5
Terms, operations, and practical uses
Memory layout
- Row-major orderRows are stored one after another; cell [r][c] is at r × cols + c.
- Column-major orderColumns are stored one after another; cell [r][c] is at c × rows + r. Used by Fortran, MATLAB, R and Julia.
- FlatteningTurning (row, col) into one memory index, and back with i / cols and i % cols.
Array structures
- Contiguous 2D arrayOne block holds the whole grid, as in C
int g[3][4]or a NumPy array. - Array of arraysA 1D array of row pointers, each row allocated on its own. Java and Python lists work this way.
- Jagged arrayAn array of arrays whose rows have different lengths, such as a triangle.
Traversal
- Nested loopsOuter loop over rows, inner loop over columns, matching row-major storage.
- Direction vectorsArrays such as dr = [-1, 1, 0, 0] and dc = [0, 0, -1, 1] that step to a cell's four neighbours in grid BFS or DFS.
- Boundary checksTest 0 <= r < rows and 0 <= c < cols before every neighbour access.
Code in Python, C++ and Java
ROWS, COLS = 2, 3
grid = [[10, 20, 30], [40, 50, 60]]
flat_array = [0] * (ROWS * COLS)
for r in range(ROWS):
for c in range(COLS):
index = (r * COLS) + c
flat_array[index] = grid[r][c]
print('Flat array:', flat_array)#include <iostream>
#include <vector>
using namespace std;
int main() {
int ROWS = 2, COLS = 3;
int grid[2][3] = {{10, 20, 30}, {40, 50, 60}};
vector<int> flat_array(ROWS * COLS);
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
int index = (r * COLS) + c;
flat_array[index] = grid[r][c];
}
}
cout << "Flat array: [";
for (size_t i = 0; i < flat_array.size(); i++) { if (i) cout << ", "; cout << flat_array[i]; }
cout << "]\n";
}class Main {
public static void main(String[] args) {
int ROWS = 2, COLS = 3;
int[][] grid = {{10, 20, 30}, {40, 50, 60}};
int[] flat_array = new int[ROWS * COLS];
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
int index = (r * COLS) + c;
flat_array[index] = grid[r][c];
}
}
System.out.println("Flat array: " + java.util.Arrays.toString(flat_array));
}
}Step through it
Running on grid = [[10, 20, 30], [40, 50, 60]], ROWS = 2, COLS = 3
Row-Major and Column-Major Order
Column-major order stores whole columns one after another, so cell [r][c] is at c × rows + r. Fortran, MATLAB, R and Julia use it. The 2 × 3 grid [[10, 20, 30], [40, 50, 60]] is stored row-major as 10, 20, 30, 40, 50, 60 and column-major as 10, 40, 20, 50, 30, 60.
The fast loop order flips with it: in column-major languages the column index goes outside and the row index inside. Code ported from C to Fortran without swapping its loops gives the right answer, slowly.
Layout matters again whenever data crosses between the two families. Passing a NumPy array to a Fortran-based LAPACK routine needs either a transpose or a flag saying which layout it is; NumPy records this as C order or F order in a.flags.
The row-major formula extends to any number of dimensions: each index is multiplied by the product of all sizes to its right. For an array sized [2][3][4], cell [1][2][3] is at 1 × 12 + 2 × 4 + 3 = 23, the last of its 24 cells. The rightmost index moves fastest, so it belongs in the innermost loop.
- Row-major: C, C++, NumPy by default; column-major: Fortran, MATLAB, R, Julia
- 3D row-major index: i × (D2 × D3) + j × D3 + k
- Sizes multiply: a 1000 × 1000 × 1000 grid of 8-byte doubles is 8 GB
Mistakes and Edge Cases
The most common slip is multiplying by the wrong size. Writing r × rows + c on a 2 × 3 grid sends (0, 2) and (1, 0) to the same slot 2, so one value overwrites the other and slot 5 is never written. Nothing crashes; the data is just wrong.
Bounds need both checks. A flat index can be in range while the column is not: on a 2 × 3 grid, (0, 4) gives index 4, which is really cell (1, 1). Check 0 <= c < cols and 0 <= r < rows separately before computing the index.
On very large grids r × cols + c can overflow a 32-bit integer: a 50,000 × 50,000 grid has 2.5 billion cells, past the 2,147,483,647 limit. Use a 64-bit index type there.
Grid problems usually come down to these same moves: Rotate Image transposes and reverses rows in place, Spiral Matrix walks the border, and Set Matrix Zeroes uses the first row and column as flags. When most cells are zero, a sparse array stores only the rest; plain one-dimensional arrays are covered in their own lesson.
- Use cols, not rows, in the row-major formula
- Check row and column ranges before flattening, not after
- Python's negative index
grid[-1]is the last row, not an error - An empty grid has rows = 0, so
grid[0]fails; test for it first