![]() |
VOOZH | about |
Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).
In the following examples, we have considered 'r' as number of rows, 'c' as number of columns and we created a 2D array with r = 3, c = 4 and the following values
1 2 3 4
5 6 7 8
9 10 11 12
1) Using a single pointer and a 1D array with pointer arithmetic:
A simple way is to allocate a memory block of size r*c and access its elements using simple pointer arithmetic.
1 2 3 4 5 6 7 8 9 10 11 12
2) Using an array of pointers
We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.
1 2 3 4 5 6 7 8 9 10 11 12
3) Using pointer to a pointer
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
1 2 3 4 5 6 7 8 9 10 11 12
4) Using double pointer and one malloc call
1 2 3 4 5 6 7 8 9 10 11 12
5) Using a pointer to Variable Length Array.
The dimensions of VLA are bound to the type of the variable. Therefore one form a pointer to an array with run-time defined shape.
The pointer has to be dereferenced before subscripting with syntax (*arr)[i][j].
1 2 3 4 5 6 7 8 9 10 11 12
6) Using a pointer to the first row of VLA
Similar to 5 but allows arr[i][j] syntax.
1 2 3 4 5 6 7 8 9 10 11 12