Dynamic Memory Allocation in C++ for 2D and 3D array

In this post, we will discuss how to dynamically allocate memory for multi-dimensional array in C++.

Single Dimensional Array
2-Dimensional Array
3-Dimensional Array

 
 

Single Dimensional Array

C++

Download   Run Code

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 pointer. Then we can use pointer arithmetic to index 2D array.

C++

Download   Run Code

2. Using Array of Pointers

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

Dynamically Allocate Memory for 2D Array

C++

Download   Run Code

3-Dimensional Array

 

1. Using Single Pointer

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

C++

Download   Run Code

2. Using Triple Pointer

C++

Download   Run Code

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz