6

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?

3
  • 4
    Duplicate: stackoverflow.com/questions/381542/…. Commented May 11, 2009 at 15:43
  • @Bastien: Thanks, I was looking for that but couldn't seem to find it. Commented May 11, 2009 at 15:45
  • This is a truly evil "feature" of C. Commented May 11, 2009 at 15:48

1 Answer 1

18

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).

Sign up to request clarification or add additional context in comments.

7 Comments

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.
Thanks a bunch - I know that's been explained to me before but couldn't quite remember it.
+1, and to be absolutely clear: a[2] == *(a+2) == 2[a] == *(2+a)
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].
Here for history: 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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.