my_function_3( p );
int (*q)[2][3][5] = &apricot;
my_function_1( *q );
my_function_2( *q );
my_function_3( *q );
Programming Challenge
Check It Out
Type in the C code in Figure 10-6 and try it for yourself.
Passing a One-Dimensional Array to a Function
One-dimensional arrays of any type can be used as function arguments in C. The parameter is
rewritten as a pointer to its first element, so you may need a convention for indicating the total size of
the array. There are two basic methods:
- Send an additional parameter that gives the number of elements (this is what argc does)
- Give the last element in the array a special value to indicate the end of data (this is what the
nul character at the end of a string does). The special value must be one that can't otherwise
occur in the data.
Two-dimensional arrays are a little bit trickier, as the array is rewritten as a pointer to the first row.
You now need two conventions, one to indicate the end of an individual row, and one to indicate the
end of all the rows. The end of an individual row can be signified by either of the two methods that
work for one-dimensional arrays. So can the end of all the rows. We are passed a pointer to the first
element of the array. Each time we increment the pointer, we get the address of the next row in the
array, but how do we know when we have reached the limit of the array? We can add an additional
row filled with some out-of-bound value that won't otherwise occur—if there is one. When you
increment the pointer, check to see if it has reached this row. Alternatively, define yet another
parameter that gives the total number of rows.
Using Pointers to Pass a Multidimensional Array to a Function
The problem of marking the extent of the array would be solvable with the ugly methods described
above. But we also have the problem of declaring the two-dimensional array argument inside the
function, and that's where the real trouble lies. C has no way to express the concept "the bounds of this
array can vary from call to call." The C compiler insists on knowing the bounds in order to generate
the correct code for indexing. It is technically feasible to handle this at runtime, and plenty of other
languages do, but this is not the C philosophy.