Programming Search⌘K

Conceptcore

Multidimensional array

Also called two-dimensional array, 2D array, matrix, nested array, array of arrays, jagged array, ragged array, rectangular array, row-major order, column-major order, Iliffe vector, ndarray, mdspan.

A multidimensional array selects an item by two or more indices, such as a row and a column. It is either one block in row-major or column-major order, or an array of separate rows.

Applies to
core-languages

Idea

A multidimensional array names each item by two or more indices. A two-dimensional array is a table or a matrix: m[r][c] is the item in row r and column c. A three-dimensional array adds a third index, such as a plane, and so on.

Memory has one dimension, so the language must put the rows somewhere. There are two common ways:

  • a dense array: all items are in one block, and the language computes one offset from all the indices. The items of each row are next to each other (row-major order) or the items of each column are next to each other (column-major order).
  • an array of arrays: an outer array holds references to separate row arrays. The rows can have different lengths, and then the array is called jagged.

Wikipedia states the difference: "In row-major order, the consecutive elements of a row reside next to each other, whereas the same holds true for consecutive elements of a column in column-major order"1.

# A 2 x 3 matrix as rows, and the same items in one flat list in two orders.
m = [[1, 2, 3],
     [4, 5, 6]]
rows, cols = 2, 3
row_major = [m[r][c] for r in range(rows) for c in range(cols)]
col_major = [m[r][c] for c in range(cols) for r in range(rows)]
print(row_major, col_major)

# The offset of item (r, c) in each order.
r, c = 1, 2
print(m[r][c], row_major[r * cols + c], col_major[c * rows + r])
Output
[1, 2, 3, 4, 5, 6] [1, 4, 2, 5, 3, 6]
6 6 6

Both flat lists hold the same six items. In row-major order, item (r, c) is at r * cols + c. In column-major order, it is at c * rows + r. All three expressions find the item 6.

How it works

Dense arrays. A dense array stores rows * cols items in one block. For row-major order, the offset of (r, c) is r * cols + c, and in general "the last dimension is contiguous"1. For column-major order, the offset is c * rows + r, and "the first dimension is contiguous"1. The number that one index is multiplied by is the stride of that dimension. NumPy describes its arrays in these terms: "An instance of class ndarray consists of a contiguous one-dimensional segment of computer memory (owned by the array, or by some other object), combined with an indexing scheme that maps N integers into the location of an item in the block"2. It adds that "The column-major order (used, for example, in the Fortran language and in Matlab) and row-major order (used in C) schemes are just specific kinds of strided scheme"2.

The order depends on the language. Wikipedia lists C and C++ (for C-style arrays), PL/I, Pascal and SAS as row-major, and Fortran, MATLAB, GNU Octave, Julia and R as column-major1.

C arrays. In C, "When the element type of an array is another array, it is said that the array is multidimensional"3. int a[2][3] is an array of 2 arrays of 3 ints, and cppreference notes that it "can be viewed as a 2x3 matrix" "with row-major layout"3. The type is an array of arrays, but the memory is one dense block: in the C example, sizeof a is 24 bytes, and the item after a[0][2] is a[1][0]. Rust [[i32; 3]; 2] and C++ std::array<std::array<int, 3>, 2> have the same layout, because a Rust array "is a fixed-size sequence of N elements of type T"4 with no gaps.

Arrays of arrays. Java, Python, JavaScript and Go slices build a table from separate row objects. Wikipedia defines a jagged array as "an array of arrays of which the member arrays can be of different lengths"5, and it notes that two-dimensional arrays are always rectangular, "so jagged arrays should not be confused with multidimensional arrays, but the former is often used to emulate the latter"5. The structure behind it has a name: "an Iliffe vector, also known as a display, is a data structure used to implement jagged arrays"6. In Java, int[][] is an array whose items are int[] objects. Each row can be replaced or be null, and a copy of the outer array shares the rows: "A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared"7.

Both forms in one language. C# has a type for each form. "An array can be single-dimensional, multidimensional, or jagged"8. int[,] is one rectangular object, and "A jagged array is an array of arrays, and each member array has the default value of null"8. For int[,], "traversal increments the indices of the rightmost dimension first, then the next left dimension, and so on, to the leftmost index"8, which is row-major order. Go also gives two choices for a slice of slices: "One is to allocate each slice independently; the other is to allocate a single array and point the individual slices into it"9. Go explains that "If the slices might grow or shrink, they should be allocated independently to avoid overwriting the next line; if not, it can be more efficient to construct the object with a single allocation"9.

Views. A view gives multidimensional indices to a block that the program owns elsewhere. C++23 added one: "std::mdspan is a multidimensional array view that maps a multidimensional index to an element of the array"10. Its default layout policy is std::layout_right10, where the rightmost index changes fastest, as in row-major order. The policy layout_left gives column-major order. A NumPy array with other strides is also a view, for example the transpose of a matrix.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaNative
CNative
C#Native
JavaScriptIdiom
TypeScriptIdiomTypeScript uses the JavaScript forms, arrays of arrays and typed arrays with an index formula, with types such as number[][]. No example file exists.
GoNative
RustNative
KotlinNativeArray<IntArray> and List<List<T>> are arrays of rows, made with Array(rows) { IntArray(cols) }. Each row is a separate object, so rows can differ in length. No example file exists because kotlinc is not installed.
SQLNativeA table with rows and columns is the usual form of two-dimensional data. PostgreSQL arrays can have more than one dimension, and a multidimensional PostgreSQL array must be rectangular.
BashDoes not applyBash arrays have one dimension. An associative array with keys such as "1,2" can imitate a table, but it is not a multidimensional array.
PowerShellNativeAn array of arrays works as in .NET, and New-Object 'int[,]' 2,3 makes a rectangular .NET array. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. The table element shows rows and columns, but it holds no data values.
CSSDoes not applyCSS Grid places elements in rows and columns. It is layout, not data.
Regular expressionsDoes not applyA regular expression matches text. It has no arrays.
Language Verdict Mechanism
Python stdlib lists of lists (jagged); NumPy ndarray for dense arrays in C or Fortran order
JavaScript idiom arrays of arrays; a typed array with an index formula for a dense matrix
TypeScript idiom the JavaScript forms with types such as number[][]
Java native int[][] is an array of row arrays, which can be jagged; a flat array for a dense matrix
Kotlin native Array<IntArray> and List<List<T>>, both arrays of rows; Array(rows) { IntArray(cols) }
C# native int[,] for a rectangular array in one object; int[][] for a jagged array
Go native [r][c]T is a dense array value; [][]T is a slice of slices, with one or many allocations
Rust native [[T; C]; R] is dense; Vec<Vec<T>> is jagged; a flat Vec<T> with an index formula
C native T a[R][C] is dense in row-major order; an array of pointers for a jagged array
C++ stdlib C arrays and std::array of std::array are dense; vector<vector<T>>; std::mdspan (C++23) views
Bash n/a arrays have one dimension; an associative array with keys such as "$r,$c" imitates a table
PowerShell native jagged arrays of arrays; New-Object 'int[,]' 2,3 makes a .NET rectangular array
SQL native a table is the usual form; PostgreSQL arrays can have many dimensions, such as int[][]
Regex n/a a pattern has no arrays
HTML n/a markup; a <table> shows rows and columns but holds no data values
CSS n/a CSS Grid lays out elements in rows and columns, but it is layout, not data

The example files show both forms. Python builds a grid with a comprehension, shows the shared-row trap with [[0] * 3] * 2, a shallow copy, a transpose with zip and a flat list in row-major order. JavaScript uses Array.from, shows that fill with an array shares one row, and uses a Float64Array as a dense matrix. Java shows new int[2][3], a jagged int[3][], a row that the program replaces, and a shallow clone. C# compares int[,], with Rank, GetLength and row-major foreach, against a jagged int[][] with null rows. Go shows that an array of arrays is copied by assignment, a slice of slices with one allocation per row, and the single-allocation method from Effective Go. Rust shows the size of a dense array, flatten, a jagged Vec<Vec<i32>> and row-major and column-major order of a flat Vec. C prints the size and the offsets of int a[2][3], walks it with one pointer, and makes a jagged array of pointers. C++ compares std::array of std::array with vector<vector<int>> and writes a small Matrix class with one vector.

PythonGitHub
# A list of lists. Each row is a separate list, so the rows can have different lengths.
grid = [[0] * 3 for _ in range(2)]
grid[0][1] = 5
print(grid, len(grid), len(grid[0]))

jagged = [[1], [2, 3], [4, 5, 6]]
print([len(row) for row in jagged], jagged[2][1])

# [[0] * 3] * 2 repeats one row object, so a write to one row shows in both.
bad = [[0] * 3] * 2
bad[0][1] = 5
print(bad, bad[0] is bad[1])

# A copy of the outer list shares the rows. A deep copy copies each row.
import copy
shallow = grid.copy()
deep = copy.deepcopy(grid)
grid[1][2] = 9
print(shallow[1], deep[1])

# zip(*m) gives the columns, which is the transpose.
m = [[1, 2, 3], [4, 5, 6]]
print([list(col) for col in zip(*m)])

# A flat list with an index formula is a dense matrix in row-major order.
rows, cols = 2, 3
flat = [0] * (rows * cols)
for r in range(rows):
    for c in range(cols):
        flat[r * cols + c] = 10 * r + c
print(flat, flat[1 * cols + 2])

# Three dimensions: a list of planes of rows.
cube = [[[x + 2 * y + 4 * z for x in range(2)] for y in range(2)] for z in range(2)]
print(cube, cube[1][0][1])
Output
[[0, 5, 0], [0, 0, 0]] 2 3
[1, 2, 3] 5
[[0, 5, 0], [0, 5, 0]] True
[0, 0, 9] [0, 0, 0]
[[1, 4], [2, 5], [3, 6]]
[0, 1, 2, 10, 11, 12] 12
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]] 5
  • Verdict: stdlib. A comprehension makes a new list for each row, so rows are independent and can differ in length. [[0] * 3] * 2 repeats one row object, so a write shows in both rows. A copy of the outer list shares the rows, and deepcopy does not. zip(*m) gives the transpose. A flat list with r * cols + c is a dense matrix, and a list of planes of rows has three dimensions.
#include <array>
#include <cstddef>
#include <iostream>
#include <vector>

// A small dense matrix: one vector and a row-major index formula.
class Matrix {
    std::size_t rows_, cols_;
    std::vector<double> data_;

public:
    Matrix(std::size_t r, std::size_t c) : rows_(r), cols_(c), data_(r * c) {}
    double& operator()(std::size_t r, std::size_t c) { return data_[r * cols_ + c]; }
    const std::vector<double>& data() const { return data_; }
};

int main() {
    // std::array of std::array is one block, like a C array.
    std::array<std::array<int, 3>, 2> a{{{1, 2, 3}, {4, 5, 6}}};
    std::cout << sizeof a << ' ' << a[1][2] << ' ' << (&a[1][0] - &a[0][0]) << '\n';

    // vector<vector<int>> has a separate heap block per row.
    std::vector<std::vector<int>> grid(2, std::vector<int>(3, 0));
    grid[0][1] = 5;
    grid[1].push_back(4);
    std::cout << grid[0].size() << ' ' << grid[1].size() << ' ' << grid[0][1] << '\n';

    Matrix m(2, 3);
    for (std::size_t r = 0; r < 2; r++)
        for (std::size_t c = 0; c < 3; c++) m(r, c) = 10.0 * r + c;
    for (double x : m.data()) std::cout << x << ' ';
    std::cout << m(1, 2) << '\n';
}
Output
24 6 3
3 4 5
0 1 2 10 11 12 12
  • Verdict: stdlib. std::array of std::array is one block of 24 bytes, like a C array. vector<vector> has a separate block per row, so one row can grow. A small Matrix class keeps one vector and computes r * cols + c.
JavaGitHub
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // new int[2][3] makes an array of 2 row arrays with 3 ints each.
        int[][] grid = new int[2][3];
        grid[0][1] = 5;
        System.out.println(Arrays.deepToString(grid) + " " + grid.length + " " + grid[0].length);

        // Each row is its own object, so rows can have different lengths and can be replaced.
        int[][] jagged = new int[3][];
        for (int i = 0; i < jagged.length; i++) jagged[i] = new int[i + 1];
        jagged[2][2] = 7;
        grid[1] = new int[] {1, 2, 3, 4};
        System.out.println(Arrays.deepToString(jagged) + " " + Arrays.deepToString(grid));

        // clone copies only the outer array. The rows are shared.
        int[][] copy = grid.clone();
        copy[0][0] = 9;
        System.out.println((copy == grid) + " " + (copy[0] == grid[0]) + " " + grid[0][0]);

        // A flat array with an index formula is one block of memory in row-major order.
        int rows = 2, cols = 3;
        int[] flat = new int[rows * cols];
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) flat[r * cols + c] = 10 * r + c;
        System.out.println(Arrays.toString(flat) + " " + flat[1 * cols + 2]);
    }
}
Output
[[0, 5, 0], [0, 0, 0]] 2 3
[[0], [0, 0], [0, 0, 7]] [[0, 5, 0], [1, 2, 3, 4]]
false true 9
[0, 1, 2, 10, 11, 12] 12
  • Verdict: native. new int[2][3] makes an array of 2 row arrays. A jagged int[3][] gets rows of different lengths, and the program can replace a row with a longer one. clone copies only the outer array, so a write through the copy changes the original. A flat int[] with an index formula is one block in row-major order.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // int a[2][3] is an array of 2 arrays of 3 ints, stored in row-major order.
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printf("%zu %zu %td\n", sizeof a, sizeof a[0], &a[1][0] - &a[0][0]);

    // The items are in one block, so a pointer to the first int walks all six in order.
    const int *p = &a[0][0];
    for (int i = 0; i < 6; i++) printf("%d ", p[i]);
    printf("\n");

    // A pointer to a row has the type int (*)[3].
    int (*row)[3] = &a[1];
    printf("%d %d\n", (*row)[2], a[1][2]);

    // A jagged array is an array of pointers to rows of different lengths.
    int r0[] = {1}, r1[] = {2, 3}, r2[] = {4, 5, 6};
    int *jag[] = {r0, r1, r2};
    int len[] = {1, 2, 3};
    for (int r = 0; r < 3; r++) printf("%d:%d ", len[r], jag[r][len[r] - 1]);
    printf("\n");

    // A matrix with sizes known only at run time: one malloc and an index formula.
    int rows = 2, cols = 3;
    int *m = malloc(sizeof *m * (size_t)rows * (size_t)cols);
    if (!m) return 1;
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++) m[i * cols + j] = 10 * i + j;
    printf("%d %d\n", m[1 * cols + 2], m[rows * cols - 1]);
    free(m);
    return 0;
}
Output
24 12 3
1 2 3 4 5 6
6 6
1:1 2:3 3:6
12 12
  • Verdict: native. int a[2][3] is 24 bytes with rows of 12 bytes, and a[1][0] is 3 items after a[0][0]. One pointer walks all six items in row-major order. A pointer to a row has the type int (*)[3]. An array of pointers to rows of different lengths is a jagged array. One malloc and an index formula make a matrix with sizes known at run time.
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // int[,] is a true two-dimensional array: one object with a fixed number of rows and columns.
        int[,] m = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine($"{m.Rank} {m.GetLength(0)} {m.GetLength(1)} {m.Length} {m[1, 2]}");

        // foreach visits the rightmost index first, which is row-major order.
        Console.WriteLine(string.Join(",", m.Cast<int>()));

        // int[][] is a jagged array: an array of separate row arrays.
        int[][] jagged = new int[3][];
        for (int i = 0; i < jagged.Length; i++) jagged[i] = new int[i + 1];
        jagged[2][2] = 7;
        Console.WriteLine($"{string.Join(" ", jagged.Select(r => r.Length))} {jagged[2][2]} {jagged.Length}");

        // A new jagged array has null rows until the program creates them.
        int[][] empty = new int[2][];
        Console.WriteLine(empty[0] is null);

        // A row of a jagged array is an array. A two-dimensional array has no row object.
        int[] row = jagged[1];
        row[0] = 9;
        Console.WriteLine($"{jagged[1][0]} {m.GetUpperBound(1)}");
    }
}
Output
2 2 3 6 6
1,2,3,4,5,6
1 2 3 7 3
True
9 2
  • Verdict: native. int[,] is one rectangular array with Rank 2, GetLength for each dimension and Length for all items. Its items come out in row-major order. int[][] is a jagged array of separate rows, and a new jagged array has null rows. A row of a jagged array is an array that the program can hold, and a write through it changes the jagged array.
JavaScriptGitHub
// An array of arrays. Array.from calls the function once per row, so each row is new.
const grid = Array.from({ length: 2 }, () => Array(3).fill(0));
grid[0][1] = 5;
console.log(grid, grid.length, grid[0].length);

// fill puts the same row object in every slot.
const bad = Array(2).fill(Array(3).fill(0));
bad[0][1] = 5;
console.log(bad, bad[0] === bad[1]);

// Rows can have different lengths.
const jagged = [[1], [2, 3], [4, 5, 6]];
console.log(jagged.map((row) => row.length), jagged[2][1], jagged[5]?.[0]);

// A typed array with an index formula is a dense matrix in row-major order.
const rows = 2, cols = 3;
const m = new Float64Array(rows * cols);
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) m[r * cols + c] = 10 * r + c;
console.log(Array.from(m), m[1 * cols + 2]);

// The transpose swaps rows and columns.
const t = [[1, 2, 3], [4, 5, 6]];
console.log(t[0].map((_, c) => t.map((row) => row[c])));
Output
[ [ 0, 5, 0 ], [ 0, 0, 0 ] ] 2 3
[ [ 0, 5, 0 ], [ 0, 5, 0 ] ] true
[ 1, 2, 3 ] 5 undefined
[ 0, 1, 2, 10, 11, 12 ] 12
[ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
  • Verdict: idiom. Array.from calls its function once per row, so each row is a new array. fill puts the same row object in every slot. Rows can differ in length, and ?. reads a missing row as undefined. A Float64Array with an index formula is a dense matrix in row-major order. A map over the columns gives the transpose.
package main

import "fmt"

func main() {
	// [2][3]int is an array of arrays. It is one value in one block, and assignment copies it.
	var a [2][3]int
	a[0][1] = 5
	b := a
	b[1][2] = 9
	fmt.Println(a, b, len(a), len(a[0]))

	// A slice of slices: allocate each row on its own, so rows can grow and differ in length.
	rows, cols := 2, 3
	grid := make([][]int, rows)
	for i := range grid {
		grid[i] = make([]int, cols)
	}
	grid[1] = append(grid[1], 4)
	fmt.Println(grid, len(grid[0]), len(grid[1]))

	// One allocation: the rows are slices of a single backing array.
	cells := make([]int, rows*cols)
	pic := make([][]int, rows)
	for i := range pic {
		pic[i], cells = cells[:cols], cells[cols:]
	}
	pic[1][0] = 7
	fmt.Println(pic)

	// A flat slice with an index formula is a dense matrix in row-major order.
	flat := make([]int, rows*cols)
	for r := range rows {
		for c := range cols {
			flat[r*cols+c] = 10*r + c
		}
	}
	fmt.Println(flat, flat[1*cols+2])
}
Output
[[0 5 0] [0 0 0]] [[0 5 0] [0 0 9]] 2 3
[[0 0 0] [0 0 0 4]] 3 4
[[0 0 0] [7 0 0]]
[0 1 2 10 11 12] 12
  • Verdict: native. [2][3]int is one value, so assignment copies all items. A slice of slices with one allocation per row lets one row grow with append. The single-allocation method from Effective Go points the rows into one backing slice. A flat slice with an index formula is a dense matrix.
RustGitHub
use std::mem::size_of;

fn main() {
    // [[i32; 3]; 2] is an array of arrays in one block: 2 * 3 * 4 bytes.
    let mut a = [[0i32; 3]; 2];
    a[0][1] = 5;
    println!("{:?} {} {}", a, a.len(), size_of::<[[i32; 3]; 2]>());

    // The rows are next to each other, so flatten gives the items in row-major order.
    let m = [[1, 2, 3], [4, 5, 6]];
    println!("{:?}", m.iter().flatten().collect::<Vec<_>>());

    // Vec<Vec<T>> has one heap block per row, and the rows can differ in length.
    let mut jagged: Vec<Vec<i32>> = (1..=3).map(|n| vec![0; n]).collect();
    jagged[2][2] = 7;
    println!("{:?} {:?}", jagged, jagged.get(5).and_then(|row| row.first()));

    // vec![row; n] clones the row, so the rows are independent.
    let mut grid = vec![vec![0; 3]; 2];
    grid[0][1] = 5;
    println!("{:?}", grid);

    // A flat Vec with an index formula is a dense matrix. Column-major order swaps the roles.
    let (rows, cols) = (2, 3);
    let flat: Vec<i32> = (0..rows * cols).map(|i| (10 * (i / cols) + i % cols) as i32).collect();
    let col_major: Vec<i32> = (0..rows * cols).map(|i| flat[(i % rows) * cols + i / rows]).collect();
    println!("{:?} {:?} {}", flat, col_major, flat[1 * cols + 2]);
}
Output
[[0, 5, 0], [0, 0, 0]] 2 24
[1, 2, 3, 4, 5, 6]
[[0], [0, 0], [0, 0, 7]] None
[[0, 5, 0], [0, 0, 0]]
[0, 1, 2, 10, 11, 12] [0, 10, 1, 11, 2, 12] 12
  • Verdict: native. [[i32; 3]; 2] is one block of 24 bytes, and flatten gives its items in row-major order. Vec<Vec> has one heap block per row, and the rows can differ in length. vec![row; n] clones the row, so the rows are independent. A flat Vec gives row-major order, and a second formula reads it in column-major order.
  • Jagged arrays. Rows of different lengths fit data such as the lines of a text or the neighbors of each node in a graph. A jagged array saves memory when the rows differ a lot.
  • Higher dimensions. The same rules work for three or more indices. In row-major order, the offset of (z, y, x) is (z * Y + y) * X + x, where Y and X are the sizes of the last two dimensions1.
  • Strided views. A view with strides can show a transpose, a column or every second row without a copy. NumPy and std::mdspan with layout_stride work this way210.
  • Sparse matrices. When most items are 0, a program stores only the others, for example in a map from (r, c) to the value, or in compressed row formats.
  • Tables in SQL. A table with columns row, col and value is a sparse matrix. A table with one column per field is a list of records, not an array.
  • Array languages. APL, NumPy and MATLAB apply operations to whole arrays of any rank. See array-oriented programming.

Pitfalls

  • Shared rows. [[0] * 3] * 2 in Python and Array(2).fill(Array(3).fill(0)) in JavaScript put the same row object in each slot. The Python FAQ explains: "replicating a list with * doesn’t create copies, it only creates references to the existing objects"11, so a write to one row "shows up in multiple places"11. Make a new row for each index with a comprehension or Array.from. The task create a two-dimensional array shows the safe form in each language.
  • Shallow copies. A copy of the outer array copies only the references to the rows. In the Java and Python examples, a change through the copy changes the original. Use a deep copy, or copy each row.
  • Loop order and the cache. A loop that visits a row-major array column by column jumps cols items at each step. The order of access "is also important for performance when traversing an array because modern CPUs process sequential data more efficiently than nonsequential data"1. Put the last index in the inner loop for row-major arrays, and the first index for column-major arrays.
  • Order across languages. A matrix from Fortran, R, MATLAB or Julia is in column-major order. When C or Python code reads the same memory, it sees the transpose unless it uses the column-major formula.
  • Null or missing rows. A new jagged array in Java or C# has null rows until the program creates them. The JLS shows a loop over { { 1, 2 }, null } that ends with a NullPointerException7.
  • Swapped indices. m[r][c] and m[x][y] have opposite meanings when x is the column. Choose one convention, such as row first, and keep it.

Cost

Operation Dense block Array of arrays
create R by C one allocation R + 1 allocations
read m[r][c] one offset computation, one memory read two memory reads: the row reference, then the item
memory R * C items R * C items, R references and R object headers
grow one row not possible without a copy of the whole block append to that row only
visit all items in storage order sequential, cache friendly sequential in each row; rows can be anywhere

A dense array is the better choice for numbers in a fixed shape, such as images and matrices. An array of arrays is the better choice when rows have different lengths or grow. For large dense arrays in a language without a dense type, a flat array and an index formula give the dense layout.

History

Fortran stores arrays in column-major order1, and numerical code written for Fortran, MATLAB and R uses that order. C made a multidimensional array an array of arrays in row-major order3, and its descendants kept this form. The array of pointers to rows is called an Iliffe vector, and "The data structure is named after John K. Iliffe"6. Java chose arrays of arrays only, so every Java two-dimensional array can be jagged7. Later languages added dense types for numerical work: C# has int[,]8, NumPy gives Python the ndarray2, and C++23 added std::mdspan10.

References

  1. Row- and column-major order, Wikipedia, Introduction; Programming languages and libraries; Address calculation in general
  2. The N-dimensional array (ndarray), NumPy reference, Internal memory layout of an ndarray
  3. Array declaration, C, cppreference.com, Multidimensional arrays
  4. Array types, The Rust Reference, type.array.intro
  5. Jagged array, Wikipedia, Introduction
  6. Iliffe vector, Wikipedia, Introduction; Data structure
  7. Chapter 10, Arrays, The Java Language Specification, Java SE 25, 10.2 Array Variables; 10.7 Array Members
  8. Arrays, C# language reference, Introduction; Multidimensional arrays; Jagged arrays
  9. Effective Go, Two-dimensional slices
  10. std::mdspan, cppreference.com, Description
  11. Programming FAQ, Python documentation, How do I create a multidimensional list?

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/25N6W4/text.yaml