c++pointersnspointerarray

I encountered some thing weird code in Dynamic memory allocation for 2D arrays in C++? please explain me what is this?


code:- p = new int *[5];
where p is a pointer & declared as int **P;

Please explain me that why there is a * in between new and [5].


Solution

  • When allocating an array using new you need to specify the type. The general pattern is:

    type* x = new type[n];
    

    Where type is the base type, x is the variable, and n is the number of entries. You can make this a pointer type by adding * to both sides:

    type** x = new type*[n];
    

    You can continue this indefinitely:

    type**** x = new type***[n];
    

    Though in practice you'd rarely see that since excessively deep structures like that are nothing but trouble.

    In C++, by virtue of its C heritage, pointers and arrays are interchangeable, as in both these definitions are basically equivalent:

    void f(int* x)
    void f(int x[])
    

    Internally you can use x as either a pointer or an array, or both:

    int y = x[0];
    int z = *x;
    

    Likewise these are identical:

    int y = x[1];
    int z = *(x + 1);
    

    In general the distinction between x[n] and *(x + n) is largely irrelevant, the compiler treats both as the same and the emitted machine code is identical. The [] notation is just a syntax element that helps make the code easier to follow.