5

Need a little help understanding what exactly is going on in this code snippet. When I run the program it prints 7.

#include <stdio.h>
int main() {
int a[] = {1,2,3,4,5,6,7,8,9};
int b[] = {1,2,3,4,5,6,7,8,9};
int c = 5;
int *p = a;
printf("--> %d", (c[b])[p]);
return 0;
}

I'm just a little confused when it comes to the (c[b])[p] part in the printf statement. Any help/explanation would be greatly appreciated.

Denny
  • 77
  • 1
  • 6
  • 3
    `c[b]` means the same as `*(c + b)`. That should help. – bzeaman Dec 14 '14 at 00:10
  • Possible duplicate of [Is array name a pointer in C?](http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c) – jww Dec 14 '14 at 00:11
  • @BennoZeeman You forgot some parentheses. They matter. i.e., see the current answer. –  Dec 14 '14 at 00:12
  • A more compleat explanation is in [With C arrays, why is it the case that a\[5\] == 5\[a\] ?](http://stackoverflow.com/questions/381542/with-c-arrays-why-is-it-the-case-that-a5-5a). – Jongware Dec 14 '14 at 00:13
  • 2
    @remyabel Thanks, you're correct. I just checked the C standard, they mention that `E1[E2]` is identical to `(*((E1)+(E2)))`. – bzeaman Dec 14 '14 at 00:19

1 Answers1

13

It's a bit weird to be written that way, but the [] operator in C is commutative. That means (c[b])[p] is the same as p[b[c]], which is a lot easier to understand:

p[b[c]] = p[b[5]] = p[6] = a[6] = 7

Doing the same with the original expression will work too, it's just a bit weird to look at in places:

(c[b])[p] = (5[b])[p] = (b[5])[p]) = 6[p] = p[6] = a[6] = 7

The commutativity (if that's a word) of [] is just due to its definition - that is, a[b] is the same as *(a + b), where you can see the order of a and b doesn't matter.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469