1

I am trying to understand why the following piece of code produces the output of 7.

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;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Promisek3u
  • 55
  • 1
  • 4

2 Answers2

6

This is pure pointer arithmatic. Read more about pointer arithmatic here and here

Just FYI, a[5] == 5[a] == *(5 + a) == *(a + 5). Related Reading.

So, in your code, c[b] == b[c] == b[5] == 6.

Then, p being equal to a, the base address of the a array, (c[b])[p] == 6[p] == 6[a] == a[6] == 7.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

Well, since c is 5, c[b] is the same as b[5], which is 6. Since p points to a, 6[p] is the same as a[6], which is 7.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278