-2

I'm trying to understand how to create a dynamic array of pointers in C++. I understand that new returns a pointer to the allocated block of memory and int*[10] is an array of pointers to int. But why to you assign it to a int**? I'm struggling to understand that.

int **arr = new int*[10]; 
coke coffee
  • 27
  • 1
  • 1
  • 2

1 Answers1

4

According to the C++ Standard (4.2 Array-to-pointer conversion)

1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

So for example if you have an array like this

int a[] = { 1, 2, 3, 4, 5 };

then in this declaration

int *p = a;

the array designator used as the initializer is implicitly converted to pointer to its first element.

So in general if you have array

T a[N];

then in expressions with rare exceptions it is converted to pointer to its first element of the type T *.

In this declaration

int **arr = new int*[10]; 

the initializer is an array elements of which has the type int *. You can introduce a typedef or an alias declaration

typedef int * T;

or

using T = int *;

So you can write

T * arr = new T[10]; 

that is the pointer arr points to the first element of the dynamically allocated array. As the elements of the array has the type int * then the type of the pointer to an element of the array is int **.

That is the operator new returns pointer to the first element of the dynamically allocated array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    While closely related, an array to pointer conversion doesn't happen in the code in the question. The type of the new-expression is already a pointer rather than an array. – eerorika Dec 21 '17 at 12:58
  • @user2079303 I described the general principle to make the understanding more clear. – Vlad from Moscow Dec 21 '17 at 15:31