A Multi-dimensional Array is essentially an "array of arrays." While a one-dimensional array represents a list, a multi-dimensional array allows you to represent data in a tabular or grid-like format. The most common form is the Two-Dimensional (2D) Array, which represents a matrix with rows and columns.
Theoretically, there is a significant difference between how we visualize a 2D array and how the computer actually stores it in memory.
Logical View (The Grid): We visualize a 2D array as a table. For example, int matrix[3][4] is seen as 3 rows and 4 columns.
Physical View (Linear Memory): Computer memory (RAM) is linear (one-dimensional). To store a 2D grid, C++ uses Row-Major Ordering. This means the computer stores the first row entirely, followed immediately by the second row, and so on.
To find an element at array[i][j], the compiler performs a calculation behind the scenes:
Theory Note: This is why you must specify the number of columns when passing a 2D array to a function—the compiler needs the column count to calculate the jump between rows.
A 2D array requires two sets of square brackets: the first for rows and the second for columns.
int matrix[3][4]; // A table with 3 rows and 4 columns (12 total elements).
You can initialize a 2D array using nested braces to make the row structure clear:
int arr[2][3] = { {1, 2, 3}, // Row 0 {4, 5, 6} // Row 1 };
If you provide fewer values than the size, the remaining elements are automatically initialized to 0.
The theoretical "partner" of a multi-dimensional array is the nested loop.
The Outer Loop usually iterates through the rows.
The Inner Loop iterates through the columns of the current row.
This program demonstrates how to use 2D arrays to perform a basic mathematical matrix operation.
#include <iostream> using namespace std; int main() { int rows = 2, cols = 2; int A[2][2] = {{1, 2}, {3, 4}}; int B[2][2] = {{5, 6}, {7, 8}}; int sum[2][2]; cout << "Calculating Matrix A + B..." << endl; // Nested loops to process the 2D structures for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { sum[i][j] = A[i][j] + B[i][j]; } } // Displaying the result cout << "Resulting Matrix:" << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << sum[i][j] << " "; } cout << endl; // New line after each row } return 0; }
C++ allows arrays of any dimension. A 3D Array (int cube[3][3][3]) can be visualized as a cube of data, or more practically, as a "book" where each row/column grid is a single "page."
Usage in Graphics: 3D arrays are used to store voxel data or RGB values for layers of an image.
Memory Growth: Be careful with high-dimensional arrays! An array like int data[100][100][100] creates 1,000,000 integers. At 4 bytes each, that is 4MB of memory instantly. If declared inside a function, this can easily cause a Stack Overflow.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION