PiyushM PiyushM - 3 months ago 10
C Question

How come we can pass an array to a function by reference without using pointers

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?

Answer

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.