prev up next   top/contents search

comp.lang.c FAQ list · Question 6.19

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


A: 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 from question 6.18 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, as in question 6.16.

See also questions 6.18, 6.20, and 6.15.

References: ISO Sec. 6.3.6
C9X Sec. 6.5.5.2


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

Hosted by Eskimo North