PASSING MULTIDIMENSIONAL ARRAYS
Wayne Throop
throopw at dg_rtp.UUCP
Sun Dec 1 05:14:13 AEST 1985
> I have an application where I want to pass a 2D array to a subroutine.
> [...I plan to...]
> do the address arithmetic [myself]. I believe that this is OK, because
> the innermost (leftmost) index is guaranteed to increase fastest, and
> C compilers are required to be consistent about packing when doing
> address arithmetic or aggregate allocation (I think).
You've got it right, except for a couple of crucial details. First, and
perhaps least important, the C language doesn't guarantee very much
about aggregate allocation. However, assuming that multidimensional
arrays are layed out as a single dimensional array with fancy address
calculations is one of the safer bets.
Second, and more important, you seem to have the address calculations
backwards. Assuming that "index x increases faster than index y" means
that a change in index "x" changes the address of the indexed array
element less than the same change in index "y" (which is the
conventional meaning of the phrase), then where you say "the innermost
(leftmost) index is guaranteed to increase fastest", you are exactly
backwards. First, a practical demonstration. This routine:
int printf();
int a[2][2];
void main(){
printf( "%o %o %o %o\n",
&a[0][0],
&a[0][1],
&a[1][0],
&a[1][1] );
}
produces this output:
16000001030 16000001032 16000001034 16000001036
on my machine, and similar output on others. To see why this is so,
just consider what the subscript operations are doing. To parenthesize,
we have
a[x][y] is equivalent to ((a[x])[y])
Now then, what is "a"? A is an array of array of int. Thus, when you
subscript "a", you get an array of int. Subscripting that, gives
(surprise) an int. Thus, the *rightmost* index "increases fastest".
Note that (as has been pointed out many times before) this is the
opposite of the case in FORTRAN.
This is often captured by the rule that "C has odometer array order,
while FORTRAN has anti-odometer array order", by analogy to the way
numbers click over on an odometer.
> Jeff
--
Wayne Throop at Data General, RTP, NC
<the-known-world>!mcnc!rti-sel!dg_rtp!throopw
More information about the Comp.lang.c
mailing list