0 day streak
cpp / intermediate
Snippet

Manual Dynamic Two-Dimensional Arrays

Dynamic 2D arrays are created by allocating an array of pointers, where each pointer then allocates an array of values on the heap.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() {
int rows = 3, cols = 3;
int** matrix = new int*[rows];
for(int i = 0; i < rows; ++i) {
matrix[i] = new int[cols];
}
matrix[1][1] = 5;
for(int i = 0; i < rows; ++i) delete[] matrix[i];
delete[] matrix;
return 0;
}
Breakdown
1
int** matrix = new int*[rows];
Allocates memory for an array of pointers (the rows).
2
delete[] matrix[i];
Each row must be manually freed before the main pointer array is deleted.