10

What is the following C code doing?

int i;
int* p = &i;
0[p] = 42;

I would have though that this would not event compile. But it even executes without a segmentation fault. So I wonder what strange use of the [] operator I have missed.

Danvil
  • 22,240
  • 19
  • 65
  • 88

3 Answers3

13

The C Standard defined the operator [] this way:

Whatever a and b are a[b] is considred as *((a)+(b))

And that's why 0[p] == *(0 + p) == *(p + 0) == p[0] which is the first element of the array.

Danvil
  • 22,240
  • 19
  • 65
  • 88
rullof
  • 7,124
  • 6
  • 27
  • 36
9

0[p] is equivalent to p[0]. Both are converted as

0[p] = *(0+p) and p[0] = *(p+0)

From above statements both are equal.

Chinna
  • 3,930
  • 4
  • 25
  • 55
7
0[p]

in 0[p] = 42;

is equivalent to p[0]

+ operation is commutative and we have:

p[0] == *(p + 0) == *(0 + p) == 0[p]
ouah
  • 142,963
  • 15
  • 272
  • 331