
address of 2D array elements?
Quote:
> in one dimension array a[6], the value a[i] is stored in address a+i
Hi QTPHA2,
Actually the compiler translates "a[i]" into "*(a+i)". This translation
is responsible for the following obscure thing in the comp.lang.c FAQ:
6.11: I came across some "joke" code containing the "expression"
5["abcdef"] . How can this be legal C?
Quote:
> What happen in multi dimension array
> for example a[2][3]?
If it is a real multidimensional array, like "inta[SIZE_Y][SIZE_X];" the
translation depends on the dimesion(s) of the array. The only dimension
that is not needed for the translation is the rightmost one. The
expression "a[y][x]" is translated into "*(a + y * SIZE_Y + x)".
Quote:
> Expecting the same as for a[i], I have tested but found that a memory of
> 2 bytes was allocated for each a[i][j] which is different from 4 bytes
> for a[i]. Furthermore, the value when printed out is not as assigned.
You should maybe post a code sample to illustrate your problem. If you
are talking about a 2D array "a", the expression "a[i]" yields a
*pointer* (the address of row i), whereas "a[i][j]" yields the array
element at position (i,j). The differing sizes in bytes result from
your compiler using different byte sizes for a pointer and your array
element data type.
The comp.lang.c FAQ contains a very good explanation of the problems
and interesting effects that occur in the context of arrays and
pointers in the section:
Section 6. Arrays and Pointers
You can get the FAQ at http://www.eskimo.com/~scs/C-faq/top.html or
at ftp://rtfm.mit.edu/pub/usenet/comp.lang.c/C-FAQ-list and it gets
posted to this newsgroup and to news.answers regularly (at the
beginning of each month).
Stephan
(initiator of the campaign against grumpiness in c.l.c)