This post will discuss dynamic memory allocation in C++ for multidimensional arrays.

1. Single Dimensional Array

The following is a simple example demonstrating dynamic memory allocation in single-dimensional arrays.

Download  Run Code

2. 2-Dimensional Array

1. Using Single Pointer

In this approach, we simply allocate one large block of memory of size M × N dynamically and assign it to the pointer. Then we can use pointer arithmetic to index the 2D array.

Download  Run Code

2. Using array of Pointers

We can dynamically create an array of pointers of size M and then dynamically allocate memory of size N for each row, as shown below:

Dynamic memory allocation in C++ for 2D array

Download  Run Code

3. 3-Dimensional Array

1. Using Single Pointer

As seen for the 2D array, we allocate memory of size X × Y × Z dynamically and assign it to a pointer. Then we use pointer arithmetic to index the 3D array.

Download  Run Code

2. Using Triple Pointer

Download  Run Code

That’s all about dynamic memory allocation in C++ for 2D and 3D arrays.