Thursday, 8 February 2018

c - What is 0[p] doing?




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.


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...