Multi-Dimensional Arrays in C++
A multi-dimensional array is an array whose elements are themselves arrays. In C++, a 2D array int a[R][C] is stored in row-major order — all elements of row 0 come first, then row 1, etc.
Memory Layout — Row-Major Order
Static & Dynamic 2D Arrays
#include <iostream>
using namespace std;
// ── Static 2D array ──────────────────────────────────────────────────
void staticExample() {
const int R = 3, C = 4;
int arr[R][C] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access arr[1][2]: row 1, column 2
cout << arr[1][2] << "\n"; // 7
cout << "Address of arr[1][2]: " << &arr[1][2] << "\n";
// Pointer arithmetic: arr+6 points to arr[1][2]
cout << *(*(arr+1)+2) << "\n"; // 7, using pointer arithmetic
}
// ── Dynamic 2D array (pointer-to-pointer) ────────────────────────────
int** alloc2D(int rows, int cols) {
int** m = new int*[rows];
for (int i = 0; i < rows; i++)
m[i] = new int[cols](); // zero-initialised
return m;
}
void free2D(int** m, int rows) {
for (int i = 0; i < rows; i++) delete[] m[i];
delete[] m;
}
// ── Flat 1D as 2D (better cache performance) ─────────────────────────
void flat2D(int rows, int cols) {
int* flat = new int[rows * cols]();
// Access flat[r][c] as flat[r*cols + c]
flat[1*cols + 2] = 99; // set [1][2] = 99
cout << flat[1*cols + 2] << "\n"; // 99
delete[] flat;
}
// ── Matrix multiplication (2D arrays) ─────────────────────────────────
void matMul(int** A, int** B, int** C, int N) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
C[i][j] = 0;
for (int k = 0; k < N; k++)
C[i][j] += A[i][k] * B[k][j]; // O(N³)
}
}
3D Arrays — Real Example: Video Frame Buffer
// 3D array: frames × rows × cols (e.g. grayscale video)
const int FRAMES = 10, ROWS = 1080, COLS = 1920;
// Static (large; usually heap-allocated):
// uint8_t video[FRAMES][ROWS][COLS];
// Dynamic 3D allocation
uint8_t*** alloc3D(int f, int r, int c) {
uint8_t*** v = new uint8_t**[f];
for (int i = 0; i < f; i++) {
v[i] = new uint8_t*[r];
for (int j = 0; j < r; j++)
v[i][j] = new uint8_t[c]();
}
return v;
}
// Access: video[frame][row][col]