A 'Strange Phenomenon' in C/C++ Arrays
Everyone is familiar with using arrays, right?
Take a look at this program, it’s quite simple.
|
|
Now look carefully at line 6.
What did you notice?
Try compiling it to see if it passes?
Let’s simplify this program even more
|
|
Now let’s look at the generated assembly code
|
|
You’re not seeing things wrong. At this moment, this array is possessed by Chuck Norris - the addresses pointed to by a[1] and 1[a] are the same, both are [ebp-10h].
Why?
Let’s recall the relationship between arrays and pointers. How do we represent arrays with pointers?
*a is a reference to the value at index 0 in array a, i.e., a[0],
So what about *(a+i)?
It should represent a reference to the value at index i in array a, i.e., a[i],
So this phenomenon shouldn’t be surprising:
Because *(a+i) == *(i+a)
Therefore a[i] == i[a]
Did you feel an aha! Insight moment?
Extended reading: “C Traps and Pitfalls” p33~p38
Original Chinese version: http://www.cppblog.com/xguru/archive/2009/12/24/103864.html