arrayscpointersvariable-assignmentincompatibletypeerror

Is this a correct way to define array of pointers to array?


Is this a correct way to define array of pointers to array in C programming language?

int* ptr[2];

int n1[5] = { 2,3,4,5,6 };
int n2[5] = { 2,3,4,5,6 };
ptr[0] = &n1;
ptr[1] = &n2;

I am getting errors like:

epi_2.c:20:12: warning: incompatible pointer types assigning to 'int *' from 'int (*)[5]' [-Wincompatible-pointer-types]
    ptr[1] = &n2;

Solution

  • You have to write

    ptr[0] = n1;
    ptr[1] = n2;
    

    Array designators used in expressions with rare exceptions are converted to pointers to their first elements.

    That is in the above statements expressions n1 and n2 have the type int * - the type of the left side expressions.

    As for these statements

    ptr[0] = &n1;
    ptr[1] = &n2;
    

    then the right side expressions have the type int ( * )[5] that is not compatible with the type int * of the left side expressions. So the compiler issues messages.

    Otherwise you need to declare the array of pointers like

    int ( * ptr[2] )[5];
    //...
    ptr[0] = &n1;
    ptr[1] = &n2;
    

    Here is a demonstration program.

    #include <stdio.h>
    
    int main( void ) 
    {
        int* ptr[2];
    
        int n1[5] = { 2,3,4,5,6 };
        int n2[5] = { 2,3,4,5,6 };
    
        ptr[0] = n1;
        ptr[1] = n2;
    
        for ( size_t i = 0; i < 2; ++i )
        {
            for ( size_t j = 0; j < 5; j++ )
            {
                printf( "%d ", ptr[i][j] );
            }
            putchar( '\n' );
        }
    }
    

    The program output is

    2 3 4 5 6 
    2 3 4 5 6 
    

    And here is another demonstration program.

    #include <stdio.h>
    
    int main( void ) 
    {
        int ( * ptr[2] )[5];
    
        int n1[5] = { 2,3,4,5,6 };
        int n2[5] = { 2,3,4,5,6 };
    
        ptr[0] = &n1;
        ptr[1] = &n2;
    
        for ( size_t i = 0; i < 2; ++i )
        {
            for ( size_t j = 0; j < 5; j++ )
            {
                printf( "%d ", ( *ptr[i] )[j] );
            }
            putchar( '\n' );
        }
    }
    

    The program output is the same as shown above

    2 3 4 5 6 
    2 3 4 5 6