Summary: In this programming example, we will learn how to declare or initialize a 2d array dynamically in C++ using the new operator.

Prerequisites:

What is Dynamic Memory Allocation?

Dynamic memory allocation is the process of allocating memory space for variables or objects on the heap during runtime.

We use dynamic memory allocation when we don’t know the number of items or amount of space required at the time of writing a program (i.e. during compile-time).

Rather we take the size or number of items as inputs during the execution ( i.e. during run time) and use it to allocate memory on the heap.

How to Create Dynamic 2D Array in C++?

In C++, we can dynamically allocate memory using the malloc(), calloc(), or new operator.

It is advisable to use the new operator instead of malloc() unless using C.

In our example, we will use the new operator to allocate space for the array.

To dynamically create a 2D array:

  1. First, declare a pointer to a pointer variable i.e. int** arr;.
  2. Then allocate space for a row using the new operator which will hold the reference to the column i.e. arr = new int*[row];.
  3. Allocate space for columns using the new operator on each row cell that will hold the actual values of array elements i.e. arr[i] = new int[col];.

We are using the pointer to pointer variable because of the following two reasons:

  • The new operator after the memory allocation process returns a pointer.
  • Array and pointers in C/C++ are kind of similar (they both hold the reference).
Array as reference

Here is the implementation of the steps in C++:

Output:

In the above program, the size of the array during compilation is unknown. We take the size as input from the user and allocate the same amount of space in the heap memory for the array.

All this allocation process occurs during the run time of the program, so the process is referred to as dynamic allocation.

In this tutorial, we learned what dynamic memory allocation is and how to dynamically create a 2D array in C++ using the new operator and a pointer to the pointer variable.

Leave a Reply