EMZETT.
Login

Multidimensional Arrays

In short: An array whose elements are themselves arrays again — this allows representing tables, matrices, or grid structures, such as a chessboard or a pixel grid.

In more detail: A two-dimensional array is addressed via two indices (row and column, e.g. field[2][5]), a three-dimensional one via three, and so on. Internally, a multidimensional array is usually nothing other than an array of arrays — every “row” can even have a different length (“jagged array”), which is rarely used for genuine matrices with a fixed width.

In Depth

chessboard = new Array[8][8]   // 8 rows, 8 columns each
chessboard[3][4] = "Rook"

A two-dimensional array can be thought of as a table: the first index selects the row, the second the column within that row. To iterate over every element, you correspondingly need two nested loops — the outer one for the rows, the inner one for the columns:

for row from 0 to 7:
    for column from 0 to 7:
        process(chessboard[row][column])

An important difference between languages: some implement multidimensional arrays as ONE contiguous block of memory with a fixed total size (a true matrix, all rows guaranteed to be the same length), others as an array of independent arrays (“jagged array” / “array of arrays”) — there, every row can theoretically have a different length, which is more flexible but also more error-prone (you can no longer blindly assume every row is the same length).

Multidimensional arrays are used beyond pure tables for anything that naturally models as a grid: image processing (every pixel has a row/column position), game boards (chess, sudoku, tic-tac-toe), or mathematical matrices for linear algebra. With more than two or three dimensions, the code quickly becomes cluttered — a more specialised data structure or library is then often worthwhile instead of a raw, multiply-nested array.

See also: Arrays, Index