This is easy to get wrong, and should make you wonder why you are using a compiler at all if you
have to do this kind of thing by hand.
In summary, therefore, if your multidimensional arrays are all fixed at the exactly same size, they can
be passed to a function without trouble. The more useful general case of arrays of arbitrary size as
function parameters breaks down like this:
- One dimension— works OK, but you need to include count or end-marker with "out-of-
bound" value. The inability of the called function to detect the extent of an array parameter is
the cause of the insecurity in gets() that led to the Internet worm. - Two dimensions— can't be done directly, but you can rewrite the matrix to a one-dimensional
Iliffe vector, and use the same subscripting notation. This is tolerable for character strings; for
other types, you need to include a count or end-marker with "out-of-bound" value. Again, it
relies on protocol agreement between caller and called routines. - Three or more dimensions— doesn't work for any type. You must break it down into a series
of lesser-dimension arrays.
The lack of support for multidimensional arrays as parameters is an inherent limitation of the C
language that makes it much harder to write particular kinds of programs (such as numerical analysis
algorithms).
Using Pointers to Return an Array from a Function
The previous section analyzed passing an array to a function as a parameter. This section examines
data transfer in the opposite direction: returning an array from a function.
Strictly speaking, an array cannot be directly returned by a function. You can, however, have a
function returning a pointer to anything you like, including an array. Remember, declaration follows
use. An example declaration is:
int (*paf())[20];
Here, paf is a function, returning a pointer to an array of 20 integers. The definition might be:
int (*paf())[20] {
int (pear)[20]; / declare a pointer to 20-int
array */
pear = calloc( 20,sizeof(int));
if (!pear) longjmp(error, 1);
return pear;
}
You would call the function like this: