Search code examples
c++arrayspointersdynamic-memory-allocation

c++ dynamic array of pointers


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

Solution

  • 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.