Andy Armstrong andy at
Fri May 11 14:34:01 BST 2007

On 11 May 2007, at 13:51, Nicholas Clark wrote:
> IIRC (and I may not well enough) there does start to be a  
> difference once
> you get beyond the first dimension - functions that take arrays to  
> arrays
> aren't quite the same thing as functions that take pointers to  
> pointers.
> (You have to provide fixed dimensions on all but the outermost  
> array, because
> implementation-wise maths is done relative to a single pointer,  
> rather than
> making n levels of pointer direction)
> (and don't expect me to remember which end is innermost. Although  
> it is the
> opposite direction from the F word)

An expression like foo = a[x][y] will compile either to something like

   foo = a[x * size of y dim + y];


   t = a[x]; foo = t[y];

depending on how a was declared.

If you declare

   int a[10][10];

you get 100 contiguous int slots and the compiler generates code to  
do the address calculations. The rightmost subscript changes fastest.

If you declare

   int *a[10];

you get 10 uninitialised pointers to integers and if you declare

   int **a;

you get a pointer to a pointer to an int.

In all cases a[x][y] is a valid expression but it generates different  
code for the int a[10][10] case.

When you declare a multi dimensional array parameter you need to  
supply the size of all but the first dimension so it can do the  
address calculation:

int spork(int a[][10]) {
    return a[3][2];

The array will still by passed as a pointer but the compiler knows  
how to do address arithmetic on it.

Shit, sometimes I even bore myself...

Andy Armstrong,

More information about the mailing list