tags:

views:

162

answers:

3

I've read this and don't believe it :) I've no compiler here to test.

+5  A: 

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
What's char+4? and what's *(chars+4)?
Juanjo Conti
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
+5  A: 

http://c-faq.com/aryptr/joke.html Try this to test compile: http://codepad.org/

micmoo
+8  A: 

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
so chars is a pointer to the begining of the my char[] array. Right?
Juanjo Conti
Yes, that's exactly what a C array is. It's a pointer to the first element of the array
Andomar
Technically 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