Search code examples
arrayscpointersmultidimensional-arrayimplicit-conversion

initialization from incompatible pointer type when assigning a pointer to a 2d array


int main()
{ 
    char artist1[4][80] = {};
    char artist2[4][80] = {};
    char (*pb1)[4][80] = artist1;
    char (*pb2)[4][80] = artist2;

    char *arrptr[2] = {pb1, pb2};
    
}

I am trying to assign a pointer to an 2d array so I can sort move the array based on the pointer. I've done this with integer arrays and it worked fine. Why am I getting this error?


Solution

  • For starters these initializers of the arrays

    char artist1[4][80] = {};
    char artist2[4][80] = {};
    

    are invalid in C before the C23 Standard. You may not use empty braces.

    You could write for example

    char artist1[4][80] = { 0 };
    char artist2[4][80] = { 0 };
    

    In this declarations

    char (*pb1)[4][80] = artist1;
    char (*pb2)[4][80] = artist2;
    

    the initializing expressions artist1 and artist2 have the type char ( * )[80] due to the implicit conversion of arrays to pointers to their first elements while the initialized objects have the type char ( * )[4][80]. So the compiler issues a message because there is no implicit conversion between objects of these pointer types.

    You should write either

    char (*pb1)[4][80] = &artist1;
    char (*pb2)[4][80] = &artist2;
    

    or (preferable)

    char (*pb1)[80] = artist1;
    char (*pb2)[80] = artist2;
    

    This declaration

    char *arrptr[2] = {pb1, pb2};
    

    is also wrong.

    If you will declare the pointers like

    char (*pb1)[80] = artist1;
    char (*pb2)[80] = artist2;
    

    then the above declaration will look like

    char ( *arrptr[2] )[80] = {pb1, pb2};