69,371
社区成员
发帖
与我相关
我的任务
分享
void* p ;
p = 0;//p指向0地址
ST2* pST2 = (ST2*)p;
char* p ;
p = 0;//p指向0地址
ST2* pST2 = (ST2*)p;
char* p ;
p = 0;
p += 1; //p指向地址为1的地方,即地址0+1的地方
ST2* pST2 = (ST2*)p;
unsigned int offset;
offset = (unsigned int) &( ( (ST2*)0)->P1 );//offset = 8
offset = (unsigned int) &( ( (ST2*)1)->P1 ) ;////offset = 9
/*
这个不是瞎搞,我的解释:
1、这里都是编译时候确定的,因为定义给出来了,那么变量的地址偏移的也是确定的
2、(ST2*)0和(ST2*)1是强制地址转换,如果熟悉c++的话,就知道以前c++中的class里面的static变量是不能用
ST2::P1,不能这样用的,就是要用0好地址的偏移,(ST2*)0)->P1
3、对数字可以强制转换来实现需要的类型比如
(int *)0,转换成int型的指针
4、之所以得到的是8和9,是因为(ST2*)0转化得到的是一个临时变量,而这样得到的是绝对地址,从0开始偏移就是8,而从1开始
当然就是9了
5、st2结构体:typedef struct
{
short b2;
int a2;
ST1 P1;
ST1 P2;
}ST2;
里面有int、short、st1、但是st1是结构体,字节对齐的时候以他内部的变量类型对齐,他里面最大的是int就是4个zijie
而st2里面最大也是int那么st2整个都是以int对齐的,到p1的时候当然偏移是8个字节
24: offset = (unsigned int) &( ( (ST2*)0)->P1 );//offset = 8
00401558 mov dword ptr [ebp-4],8
25: cout << offset << "\n";
0040155F push offset string "\n" (0047201c)
00401564 mov eax,dword ptr [ebp-4]
00401567 push eax
00401568 mov ecx,offset std::cout (0047ff88)
0040156D call @ILT+240(std::basic_ostream<char,std::char_traits<char> >::operator<<) (004010f5)
00401572 push eax
00401573 call @ILT+615(std::operator<<) (0040126c)
00401578 add esp,8
26: offset = (unsigned int) &( ( (ST2*)1)->P1 ) ;////offset = 9
0040157B mov dword ptr [ebp-4],9