0

It is tested and obvious that the following code won't work as we are initialising an array q[][4] with the address of first element of an array a.

    int main()
{
    int a[3][4] =
    {
        1, 2, 3, 4,
        5, 6, 7, 8,
        9, 0, 1, 6
    } ;
    int q[ ][4]=a;
    int i,j;
    for(i=0; i<3; i++)
    {
        for(j=0;j<4;j++)
        {
            printf("%d",q[i][j]);
        }

    }
    return 0;
}

But, If we implement the same logic using functions(ie passing address of array a to a formal parameter q[][4] of a function) then it works fine.

main( )
{
    int a[3][4] =
    {
        1, 2, 3, 4,
        5, 6, 7, 8,
        9, 0, 1, 6
    } ;

    print ( a, 3, 4 ) ;
}

    print ( int q[ ][4], int row, int col )
    {
        int i, j ;
        for ( i = 0 ; i < row ; i++ )
        {
            for ( j = 0 ; j < col ; j++ )
                printf ( "%d ", q[i][j] ) ;
            printf ( "\n" ) ;
        }
        printf ( "\n" ) ;
    }

how come it is possible?

PiyushM
  • 23
  • 6

1 Answers1

1

int q[ ][4] in function argument is equivalent to int (*q)[4] (pointer to 4-element array of int). N1570 6.7.6.3 Function declarators (including prototypes), paragraph 7 says:

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

Also a used for the function argument is converted to a pointer pointing at the first element of the array, which is 4-element array of int. N1570 6.3.2.1 Lvalues, arrays, and function designators. paragraph 3 says:

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

Therefore, the function print() can know where the elements of the array is and work with it.

By the way, don't forget to declare functions (or including headers in which they are declared) before the line that use the functions.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 1
    While this is a technically correct quotation from the N1570 draft of C11, you chose to reference [one of the only parts](http://stackoverflow.com/a/15737472/4520911) (N1570 6.3.2.1 p3) of the draft that differed in meaning from the final. I would suggest annotating your draft to reflect the changes listed (for myself, I just did a strike-through of the `_Alignof` text anywhere where there was a change) just in case you reference this part again for Stack Overflow, or for personal reference ;-). The only difference in your citation of N1570 6.3.2.1 p3 was _"the `_Alignof` operator"_ part. – iRove Aug 18 '16 at 04:11