Expert C Programming

(Jeff_L) #1

About the best we can do is to give up on two-dimensional arrays and change array[x][y] into a
one-dimensional array[x+1] of pointers to array[y]. This reduces the problem to one we have
already solved, and we can store a null pointer in the highest element array[x+1] to indicate the
end of the pointers.


Software Dogma


There Is No Way in C to Pass a General Multidimensional Array to a Function


This is because we need to know the size of each dimension, to do the correct scaling for
address arithmetic. There is no way in C of communicating this data (which will change
with each call) between the actual and formal parameters. You therefore have to give the
size of all but the leftmost dimension in the formal parameter. That in turn restricts the
actual parameter to arrays where all but the leftmost dimension must match in size.


invert_in_place( int a[][3][5] );


can be called by either of:


int b[10][3][5]; invert_in_place( b );


int c[999][3][5]; invert_in_place( c );


But arbitrary 3-dimensional arrays like:


int fails1[10][5][5]; invert_in_place( fails1 );/* does


NOT compile */


int fails2[999][3][6]; invert_in_place( fails2 );/* does


NOT compile */


fail to compile.


Arrays of two or more dimensions cannot be used as parameters in the general case in C. You cannot
pass a general multidimensional array to a function. You can pass specific arrays of known
prespecified size, but it cannot be done in the general case.


The most obvious way is to declare a function prototype like this:


Attempt 1


my_function( int my_array [10][20] );

Free download pdf