大家对数组的使用再熟悉不过了吧?
来看下这个程序,挺简单的。
1
#include<iostream>
2
int main()
3

{
4
int a[] =
{1,2,3,4,5};
5
for(int i = 0 ; i < 5; i++)
6
std::cout << i[a] << " ";
7
return 0;
8
}
现在请仔细看第6行。
发现了什么?
试下编译一下看能不能通过?
把这个程序更加简化
1
int a[5] =
{1,2,3,4,5};
2
int b = 1[a];
再来看下产生的汇编代码
4: int a[5] = {1,2,3,4,5};
00401568 mov dword ptr [ebp-14h],1
0040156F mov dword ptr [ebp-10h],2
00401576 mov dword ptr [ebp-0Ch],3
0040157D mov dword ptr [ebp-8],4
00401584 mov dword ptr [ebp-4],5
5: int b = 1[a];
0040158B mov eax,dword ptr [ebp-10h]
0040158E mov dword ptr [ebp-18h],eax
你没有看错,此刻这个数组春哥附体,a[1]的指向地址和1[a]是一样的,都是[ebp-10h]。
Why?
我们回忆一下数组和指针的关系,如何用指针来表示数组?
*a 就是 数组 a中下标为0的值的引用,即a[0],
那么*(a+i) 呢?
表示的就应该是数组 a中下标为i的值的引用了,即a[i],
那么这种现象也不足为怪了:
因为 *(a+i) == *(i+a)
所以 a[i] == i[a]
是不是感到 啊哈!灵机一动(aha! Insight)了呢?
扩展资料:《C陷阱与缺陷》p33~p38