c - array indexing method a tricky case -


#include<stdio.h> int main() { int buff[] = {1,2,3,4,5,6,9,10}; char c = (buff+1)[5]; printf("%d\n",c);//output 9 return 0; } 

can explain how happening , why

recall:

in c square braces [ ] implicitly *( ... ).


what going on in snippet of code provided not obvious pointer arithmetic. line:

char c = (buff+1)[5]; 

... equivalent following (by c standard):

char c = *( ( buff + 1 ) + 5 ); 

... points 7th element in array (6th position) , dereferences it. should output 9, not 19.

remark:

following note square braces, it's important see following equivalent.

arr[ n ] <=> n[ arr ] 

... arr array , n numerical value. more complicated example:

' '[ "]; < 0; i++; while ( 1 ); awesome (y)." ]; 

... of entirely valid pointer arithmetic.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -