Expert C Programming

(Jeff_L) #1

How Array and Pointer Parameters Are Changed by the Compiler


The "array name is rewritten as a pointer argument" rule isn't recursive. An array of arrays
is rewritten as a "pointer to arrays" not as a "pointer to pointer".


Argument is: Matches Formal Param:
array of array char c[8][10];^ char (*c)[10];^ pointer to array
array of pointer char *c[15];^ char **c;^ pointer to pointer
pointer to array char (*c)[64];^ char (*c)[64];^ doesn't change
pointer to pointer char **c;^ char **c;^ doesn't change

The reason you see char argv is that argv is an array of pointers (i.e., char
argv[]). This decays into a pointer to the element, namely a pointer to a pointer. If the
argv parameter were actually declared as an array of arrays (say, char
argv[10][15]) it would decay to char (
argv)[15] (i.e., a pointer to an array of
characters) not char
argv.


For Advanced Students Only


Take a moment to refer back to Figure 9-8, "Multidimensional Array Storage," on page 255. See how the
variables labelled "compatible type" down the left side of that diagram exactly match how you would
declare the corresponding array as a function argument (shown in the table above).


This is not too surprising. Figure 9-8 shows how an array name in an expression decays into a pointer; the
table above shows how an array name as a function argument decays into a pointer. Both cases are
governed by a similar rule about an array name being rewritten as a pointer in that specific context.


Figure 10-6 shows all combinations of valid code. We see:



  • all three functions take same type of argument, an array [2][3][5] or a pointer to an array[3][5]
    of int.

  • all three variables, apricot, p, *q match the parameter declaration of all three functions.


Figure 10-6 All Combinations of Valid Code


my_function_1( int fruit [2][3][5] ) { ; }


my_function_2( int fruit [][3][5] ) { ; }


my_function_3( int (*fruit)[3][5] ) { ; }


int apricot[2][3][5];


my_function_1( apricot );


my_function_2( apricot );


my_function_3( apricot );


int (*p) [3][5] = apricot;


my_function_1( p );


my_function_2( p );

Free download pdf