TheLearner
TheLearner

Reputation: 15

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.

Upvotes: 1

Views: 8876

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

int** array is a pointer to a pointer to an int. So by doing this:

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

you are creating a section of memory that holds n int* pointers and pointing array at that memory. For each of these pointers that you have created, it is possible to create a set of ints like so:

for (auto i = 0; i < n; ++i)
    array[i] = new int[n];

The resulting memory will look like this:

array -> [       int*     |     int *     |   .... n
         [int | int | ...][int | int | ...][  ... n

This is however, much much easier if you use some of the std things in c++, ie a std::vector :

std::vector<std::vector<int>> arr(std::vector<int>(0, n), n);

and you are done ...

Upvotes: 3

The Quantum Physicist
The Quantum Physicist

Reputation: 26276

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];

Upvotes: 5

Related Questions