Thursday 19 October 2017

arrays - Why is 2[myArray] valid C syntax?





Duplicate






href="https://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a">In
C arrays why is this true? a[5] == 5[a]




/>

Given an
array



 myArray[5] = { 0, 1, 2, 3,
4 };



an
element can be accessed as




2[myArray]


Why? When I
see this expression I'm imagining C trying to access the pointer "2" and failing to add
"myArray" pointer increments to dereference that address. What am I
missing?



Answer




in C, a[b] is equivalent to *(a + b). And, of
course, the + operator is commutative, so a[b] is the same as b[a] is the same as *(b +
a) is the same as *(a + b).



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...