views:

175

answers:

1

Duplicate

In C arrays why is this true? a[5] == 5[a]


Given an array

 myArray[5] = { 0, 1, 2, 3, 4 };

an element can be accessed as

 2[myArray]

Why? When I see this expression I'm imagining C trying to access the pointer "2" and failing to add "myArray" pointer increments to dereference that address. What am I missing?

+17  A: 

in C, a[b] is equivalent to *(a + b). And, of course, the + operator is commutative, so a[b] is the same as b[a] is the same as *(b + a) is the same as *(a + b).

Chris Young
It's worth to point out that in C, myArray is essentially an int variable that contains a pointer address, which is why this property works. The brackets tell it to evaluate the pointer to find the data at the addressed memory block. It doesn't try to access the memory first, and then add the index; it adds the pointer and index together and then accesses the memory. This approach is much more efficient, as you're not accessing two addresses, just one.
Eric
Thanks a bunch - I know that's been explained to me before but couldn't quite remember it.
Mitch Flax
+1, and to be absolutely clear: a[2] == *(a+2) == 2[a] == *(2+a)
dwc
Eric: The way arrays (and indeed pointers) are implemented is up to the implementation. It needn't, and often isn't, be represented anything like an int. A pointer might take up more space than can fit in an int. This is typical, but not required, in current 64 bit systems for example. Furthermore, far pointers in DOS systems were typically represented as two 16 bit words (separate segment and offset). Pointers are not arithmetic types and cannot portably be converted to and from int.
Chris Young
Wow, that's amazing - 25 years of 'variables names cannot start with a numeral' out the window.
KevinDTimm
kevindtimm: I think you're a bit confused. You are correct that variables (identifiers) cannot start with a numeral. With 3[a] you have an identifier spelled 'a', there is no numeral in it. It is semantically identical to *(3 + a) which is identical to *(a + 3) which is identical to a[3].
Chris Young
Here for history: http://cm.bell-labs.com/cm/cs/who/dmr/chist.html . It was V!i for BCPL, which indexed an array V at index i. the symmetry showed directly there.
Johannes Schaub - litb