### Question 6.18

My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.

The rule (see question 6.3) by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully; see also question 6.13. (The confusion is heightened by the existence of incorrect compilers, including some old versions of `pcc` and `pcc`-derived `lint`s, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.)

If you are passing a two-dimensional array to a function:

    	int array[NROWS][NCOLUMNS];
    	f(array);

the function's declaration must match:

    	f(int a[][NCOLUMNS])
    	{ ... }

or

    	f(int (*ap)[NCOLUMNS])	/* ap is a pointer to an array */
    	{ ... }

In the first declaration, the compiler performs the usual implicit parameter rewriting of ``array of array'' to ``pointer to array'' (see questions 6.3 and 6.4); in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of rows, `NROWS`, can be omitted. The ``shape'' of the array is still important, so the column dimension `NCOLUMNS` (and, for three- or more dimensional arrays, the intervening ones) must be retained.

If a function is already declared as accepting a pointer to a pointer, it is probably meaningless to pass a two-dimensional array directly to it.

See also questions 6.12 and 6.15.

References: K&R1 Sec. 5.10 p. 110
K&R2 Sec. 5.9 p. 113
H&S Sec. 5.4.3 p. 126

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback