Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 0[p] doing? [duplicate]

Tags:

c

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.

like image 740
Danvil Avatar asked Dec 27 '13 13:12

Danvil


1 Answers

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.

like image 73
rullof Avatar answered Nov 15 '22 19:11

rullof