I've read this and don't believe it :) I've no compiler here to test.
Asked
Active
Viewed 421 times
3 Answers
9
In raw C, the []
notation is just a pointer math helper. Before []
, you'd look for the fourth char in the block pointed to by ptr
like:
*(ptr+4)
Then, they introduced a shortcut which looked better:
ptr[4]
Which transaltes to the earlier expression. But, if you'd write it like:
4[ptr]
This would translate to:
*(4+ptr)
Which is indeed the same thing.

Andomar
- 232,371
- 49
- 380
- 404
-
so chars is a pointer to the begining of the my char[] array. Right? – Juanjo Conti Nov 21 '09 at 20:28
-
Yes, that's exactly what a C array is. It's a pointer to the first element of the array – Andomar Nov 21 '09 at 20:33
-
4Technically not quite - see: http://www.lysator.liu.se/c/c-faq/c-2.html (but for the purposes of this answer, they're close enough!) – SimonJ Nov 21 '09 at 20:38
5
Because a[b] is exactly the same as *(a+b), and + is commutatitve.
chars[4]
is *(chars+4)
, and 4[chars]
is *(4+chars)

Ned Batchelder
- 364,293
- 75
- 561
- 662
-
-
char + 4 is a pointer to the fourth character in the array and *(chars+4) dereferences this pointer to give the character at the chars[4] location – rzrgenesys187 Nov 21 '09 at 20:25
4
http://c-faq.com/aryptr/joke.html Try this to test compile: http://codepad.org/

micmoo
- 5,991
- 3
- 22
- 16