Interview Questions

My compiler complained when I passed a two-dimensional array

C Interview Questions and Answers


(Continued from previous question...)

My compiler complained when I passed a two-dimensional array

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

A:The ruleby 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;
If you are passing a two-dimensional array to a function:
int array[NROWS][NCOLUMNS];
f(array);
the function's declaration must match:
void f(int a[][NCOLUMNS])
{ ... }
or
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'' 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).

(Continued on next question...)

Other Interview Questions