tags:

views:

118

answers:

3

I understand the basic idea that when an array is the sole operand of the & or sizeof() operator, it decays to a pointer to the first element in the array. I'm unsure how these notations work though. In our text, there is the 1-D case, vs the 3-D case for an array. The first example is the function declaration for a function called average. The 1-D case is

double average(double set[]) or
double average(double *set)

Those make sense to me. The equivalent multi-D case does not. Their declaration is

double average (double set[][DIM1][DIM2]) or
double average (double (*set)[DIM1][DIM2])

Similarly, the function declaration for printing a value for 1-D is:

double *printvalue(double value)

The multi-D case is:

double (*printvalue(double value))[DIM1][DIM2]

Can anyone shed any light on this? Thanks.

A: 

The parameter still decays to a pointer. The important part is that DIM1 and DIM2 specify the size of all but one dimension. So, if we have:

double average (double set[][DIM1][DIM2] myset)

myset[0][0] is DIM2 * sizeof(double) before myset[0][1]. Together, the two dimensions say that myset[0] is DIM1 * DIM2 * sizeof(double) before myset[1]. You don't need a DIM0 on the left, because the number of rows doesn't affect the pointer arithmetic. You can always leave out the leftmost dimension for this reason.

Matthew Flaschen
A: 

Check this out http://www.eskimo.com/~scs/cclass/int/sx9.html

Ravisha
A: 

You can still obtain value of pointer to chosen node of the array. The difference if whether you get the address alone (value, taken from the compiler), or value of a real pointer (a variable residing somewhere in memory). This also implies memory layout.

In case of an array with empty [] braces and initializer the pointer itself won't exist, just its value: For char a[] = {1,2}; the value of a will be the memory location of a[0], equivalent to &a[0]. But you can't get char** b = &a, location of the pointer, as you could with char* a = {1,2}.

Also, pure array guarantees continuity of memory. You can call any element like this:

 int values[MAX_Y][MAX_X];

or like this:

 int values_flat[MAX_Y*MAX_X]; 
 #define values(x,y) = (*( values_flat + MAX_X * (y) + (x) ))

These are equivalent internally. One continuous block of memory with its structure being an arbitrary choice of the compiler.

Not so with

 int* values[MAX_VAL];

This is really MAX_VAL pointers to arbitrary locations in memory. values[0][MAX_VAL] in case of array[][] would equal values[1][0]. In case of array of pointers, it could point to an arbitrary memory location outside of allocated space.

SF.
Even though C guarantees contiguity in the "array or array" case, `values[0][MAX_VAL]` is undefined because you're using an out-of-bounds index. It is true that `values[0] + MAX_VAL == values[1]`, though :-). See http://stackoverflow.com/questions/2036104 for a discussion.
Alok