Interview Questions

How do I write functions which accept two-dimensional arrays when the width is not known at compile time?

C Interview Questions and Answers


(Continued from previous question...)

How do I write functions which accept two-dimensional arrays when the width is not known at compile time?

It's not always easy. One way is to pass in a pointer to the [0][0] element, along with the two dimensions, and simulate array subscripting ``by hand'':
void f2(int *aryp, int nrows, int ncolumns)
{ ... array[i][j] is accessed as aryp[i * ncolumns + j] ... }

Note that the correct expression for manual subscripting involves ncolumns (the ``width'' of each row), not nrows (the number of rows); it's easy to get this backwards.
This function could be called with the array as
f2(&array[0][0], NROWS, NCOLUMNS);

It must be noted, however, that a program which performs multidimensional array subscripting ``by hand'' in this way is not in strict conformance with the ANSI C Standard; according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS.
C99 allows variable-length arrays, and once compilers which accept C99's extensions become widespread, VLA's will probably become the preferred solution. (gcc has supported variable-sized arrays for some time.)
When you want to be able to use a function on multidimensional arrays of various sizes, one solution is to simulate all the arrays dynamically

(Continued on next question...)

Other Interview Questions