To declare or initialize a 2d array in c++, we need to use pointers. So let’s understand what a pointer is in C++?

Pointers in C++

A pointer in C++ can be considered as a variable/Object which stores the address of other variables/object or function.

pointers in c++

Hence, now we can access the values of those variables or objects whose address is stored in the pointer variable.

Why use Pointers?

  • Through Pointers, We can access a variable which is declared outside the function. Those variables can’t be accessed by names because they are not in the scope.
  • Pointers can be used in the array very efficiently.
  • We can allocate memory dynamically in the heap or free store. Since memory doesn’t have any variable name, It can only be accessed via pointers.

Now you know why we will use a pointer for dynamic allocation of the array. Because it’s only the way.

Array vs Pointers

Array and pointers are kind of similar. They both hold the reference to other location/variable having some value.

You may feel amazed by knowing this for the first time. But its true. Take a re-look at the code in the display() function. I am using subscript on pointers i.e a[i][j] to print its value.

We were used to doing this with array right? then why we are doing the same with the pointers because array itself is a pointer. Take a look at the image below.

array vs pointers

The same thing we are doing using pointers. We are using a pointer to pointer variable to store the address of the first element of every row. And the first element of every row will store the address of the first element of the 1D array.

Hence we traverse pointers using array subscript and use it to read and store the values of each array element.

Dynamic 2D Array in C++ Code


That’s all for a 2-dimensional array dynamic initialization tutorial. If you have any doubts then comment below.

Leave a Reply