-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]; 
3
  • 1
    If int[] decays to int*, then int*[] would decay to int**. Commented Dec 21, 2017 at 12:36
  • 1
    You usually do T *arr = new T[N];. If T is int, then it becomes int *arr = new int[N];. If T is int *, then it becomes int **arr = new int*[N];. Commented Dec 21, 2017 at 12:37
  • 1
    Use std::vector, not new[].
    – user2672107
    Commented Dec 21, 2017 at 13:38

1 Answer 1

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.

2
  • 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
    Commented Dec 21, 2017 at 12:58
  • @user2079303 I described the general principle to make the understanding more clear. Commented Dec 21, 2017 at 15:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.