Expert C Programming

(Jeff_L) #1

Although this is the simplest way, it is also the least useful, as it forces the function to process only
arrays of exactly size 10 by 20 integers. What we really want is a means of specifying a more general
multidimensional array parameter, such that the function can operate on arrays of any size. Note that
the size of the most significant dimension does not have to be specified. All the function has to know
is the sizes of all the other dimensions, and the base address of the array. This provides enough
information to "step over" a complete row and reach the next one.


Attempt 2


We can legally drop the first dimension, and declare our multidimensional array as:


my_function( int my_array [][20] );


This is still not good enough, as all the rows are still constrained to be exactly 20 integers long. The
function could equally be declared as:


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


The brackets around (* my_array) in the parameter list are absolutely necessary to ensure that it is
translated as a single pointer to a 20-element array of int's, and not an array of 20 pointers-to-int.
Again, though, we are tied to an array of size twenty in the rightmost dimension.


Software Dogma


Conformant Arrays


As originally designed, Pascal had the same functionality gap as C—there was no way to
pass arrays of different sizes to the same function. In fact Pascal was worse, because it
could not even support the case of one-dimensional arrays, which C can. Array bounds were
part of the signature of a function, and a type mismatch would occur if argument sizes did
not match in all respects. Pascal code like the following failed:


var apple : array[1..10] of integer;


procedure invert( a: array[1..15] of integer);


invert(apple); { fails to compile! }


To repair this defect, the Pascal standardization language-meisters dreamed up a concept
called conformant arrays—a better name would have been confuse 'em arrays. It's a
protocol for communicating array sizes between actual and formal parameters. It's not
immediately apparent to normal programmers how it works, and it's not in any other
mainstream languages. You have to write code like the following:

Free download pdf