Search code examples
cpointersmultidimensional-arraydeclarationimplicit-conversion

Difference between these pointers


I wrote this C code

int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int *P[3] = A;

which gives an error. However when I modify the pointer like this

int (*P)[3] = A;

The code compiles. What is the difference between these two pointers


Solution

  • This declaration

    int *P[3]
    

    does not declare a pointer. It declares an array of three elements of the type int *.

    You may even rewrite this declaration of the array the following way

    int * ( P[3] )
    

    However you may not initialize one array with another array even of the same type except that you may initialize character arrays with string literals.

    This declaration

    int (*P)[3]
    

    indeed declares a pointer to an object of the array type int[3]. On the other hand the initializer used in this declaration

    int (*P)[3] = A;
    

    and that has the type int[2][3] is implicitly converted to pointer to its first element of the type int ( * )[3] (that is to the array {1, 2, 3}). So the declared object and the initializing expression have the same type int ( * )[3].