#include<iostream>
using namespace std;
struct S
{
int a;
int *p;
};
S s;
int main()
{
int *temp=&s.a;
temp[0]=10;
temp[1]=12;
s.p=temp;
s.p[1]=20;
s.p[0]=120;//报错
return 0;
}
请问最后s.p[0]=120;为什么会报错?
原因如下:
temp=00477738
&temp=0012FF7C
s.p=00477738
&s.p=0047773C
s.p[0]=10//因为temp[0]=10
&s.p[0]=00477738
s.p[1]=4683576
&s.p[1]=0047773C
可见temp=&s.p[0]=s.p;&s.p=&s.p[1]
反汇编如下:
12: int *temp=&s.a;
00401048 mov dword ptr [ebp-4],offset s (00432e08)
13: temp[0]=10;
0040104F mov eax,dword ptr [ebp-4]
00401052 mov dword ptr [eax],0Ah
14: temp[1]=12;
00401058 mov ecx,dword ptr [ebp-4]
0040105B mov dword ptr [ecx+4],0Ch
15: s.p=temp;
00401062 mov edx,dword ptr [ebp-4]
00401065 mov dword ptr [s+4 (00432e0c)],edx
16: s.p[1]=20;
0040106B mov eax,[s+4 (00432e0c)]
00401070 mov dword ptr [eax+4],14h
17: s.p[0]=120;
00401077 mov ecx,dword ptr [s+4 (00432e0c)]
0040107D mov dword ptr [ecx],78h
18:
19: return 0;
00401083 xor eax,eax
20: }
00432E08 0A 00 00 00 14 00 00 ----------------------08 2E 43 变成了14 00 00(注意变量在内存中的存放方式,低位在前,高位在后)
00432E0F 00 00 00 00 00 00 00
00432E16 00 00 24 E0 42 00 20
--------------------
因篇幅问题不能全部显示,请点此查看更多更全内容