TheLearner TheLearner - 2 months ago 15
C++ Question

Declaring a 2D array using double pointer

I am confused about this line in a C++ program. The idea of the program is to check whether a

4x4
array is symmetric or not. This part of the code declares a 2D array, which I do not understand.

int** array = new int*[n];


Although, there is another question similar to this but it is about single pointer which I get.

int *array = new int[n];


I do not understand the double pointer. Kindly explain.

Answer

How do you create a single pointer array? You do this:

int* myArray = new int[n];

What does this mean? It has two parts. First part is reserving a pointer int* we call it myArray, and the second part is that you reserve n elements, each with size int in memory (this is an array, right?), and you take the address of that array and you save it in the variable myArray.

Now you want a 2D array, which is an array of an array. So Every element of this new array of array is one of these, that we talked about up there. How do we reserve this? We do:

new int*[n];

Because we are reserving n slots, each with type int*, that we talked about before.

Now what is the type of the return value? It's an array of an array, or a "pointer to an array, and the latter is also a pointer to an array", so you write it as

(int*)*

Or

int**

so it becomes

int** array = new int*[n];
Comments