prev up next   top/contents search

comp.lang.c FAQ list · Question 6.20

Q: How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions?


A: There is no single perfect method. Given the declarations

	int array[NROWS][NCOLUMNS];
	int **array1;			/* ragged */
	int **array2;			/* contiguous */
	int *array3;			/* "flattened" */
	int (*array4)[NCOLUMNS];

int (*array5)[NROWS][NCOLUMNS];
with the pointers initialized as in the code fragments in question 6.16, and functions declared as
	void f1a(int a[][NCOLUMNS], int nrows, int ncolumns);
	void f1b(int (*a)[NCOLUMNS], int nrows, int ncolumns);
	void f2(int *aryp, int nrows, int ncolumns);
	void f3(int **pp, int nrows, int ncolumns);
where f1a and f1b accept conventional two-dimensional arrays, f2 accepts a ``flattened'' two-dimensional array, and f3 accepts a pointer-to-pointer, simulated array (see also questions 6.18 and 6.19), the following calls should work as expected:
	f1a(array, NROWS, NCOLUMNS);
	f1b(array, NROWS, NCOLUMNS);
	f1a(array4, nrows, NCOLUMNS);
	f1b(array4, nrows, NCOLUMNS);

f1(*array5, NROWS, NCOLUMNS);
f2(&array[0][0], NROWS, NCOLUMNS); f2(*array, NROWS, NCOLUMNS); f2(*array2, nrows, ncolumns); f2(array3, nrows, ncolumns); f2(*array4, nrows, NCOLUMNS);
f2(**array5, NROWS, NCOLUMNS);
f3(array1, nrows, ncolumns); f3(array2, nrows, ncolumns);
The following calls would probably work on most systems, but involve questionable casts, and work only if the dynamic ncolumns matches the static NCOLUMNS:
	f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
	f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
	f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);
	f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);

It will be noticed that only f2 can conveniently be made to work with both statically- and dynamically-allocated arrays, though it will not work with the traditional ``ragged'' array implementation, array1. However, it must also be noted that passing &array[0][0] (or, equivalently, *array) to f2 is not strictly conforming; see question 6.19.

If you can understand why all of the above calls work and are written as they are, and if you understand why the combinations that are not listed would not work, then you have a very good understanding of arrays and pointers in C.

Rather than worrying about all of this, one approach to using multidimensional arrays of various sizes is to make them all dynamic, as in question 6.16. If there are no static multidimensional arrays--if all arrays are allocated like array1 or array2 in question 6.16--then all functions can be written like f3.

Additional links: Sample source code (``torture test'') illustrating all these techniques


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

Hosted by Eskimo North