Search code examples
c++arrayspointersincompatibletypeerror

Why does float** cannot initialize with float(*)[5]?


The following code is invalid:

int main()
{
    int n =5;
    float ** p = new float[n][5]; //error: cannot initialize a variable of type 
                                  //'float **' with an rvalue of type 'float (*)[5]'
}

demo

I expected that after applying new operator to float[n][5], float** will be returned. So what exactly type will be returned by new float[n][5]?

UPD: The following code is valid:

int main()
{
    float* p[5];
    float ** t = p; //OK
}

demo


Solution

  • The error message showed what is the returned type

    float (*)[5]
    

    That is it is pointer to an array with 5 elements of type float.

    As for float ** then it is pointer to a pointer to an object of type float, To see the difference execute the following code

    float ( *p1 )[5];
    float **p2;
    
    std::cout << sizeof( *p1 ) << std::endl;
    std::cout << sizeof( *p2 ) << std::endl;
    

    It is the values that are used in the pointer arithmetic, For example if p1 was initialized then ++p1 will have an address that is sizeof( *p1 ) greater than the initial address

    That it would be more clear consider the following code

    typedef float T1[5];
    typedef float *T2;
    
    std::cout << sizeof( T1 ) << std::endl;
    std::cout << sizeof( T2 ) << std::endl;
    
    T1 *p1 = new T1[5];
    T2 *p2 = new T2[5];