prev up next   top/contents search

comp.lang.c FAQ list · Question 6.18

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

A: The rule (see question 6.3) by which arrays decay into pointers is not applied recursively. (Once the rule has been applied once, the result is a pointer to which the rule no longer applies.) 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.

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

	int array[NROWS][NCOLUMNS];
the function's declaration must match:
	void f(int a[][NCOLUMNS])
	{ ... }
	void 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 width 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 almost certainly meaningless to pass a two-dimensional array directly to it. An intermediate pointer would have to be used when attempting to call it with a two-dimensional array:

	extern g(int **ipp);

	int *ip = &array[0][0];
	g(&ip);		/* PROBABLY WRONG */
but this usage is misleading and almost certainly incorrect, since the array has been ``flattened'' (its shape has been lost).

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

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North