示例
struct MyStruct {
int a;
float b;
char c;
};
size_t offset = (size_t) & (((MyStruct*)0)->a);
std::cout << offset << std::endl;
offset = (size_t) & (((MyStruct*)0)->b);
std::cout << offset << std::endl;
offset = (size_t) & (((MyStruct*)0)->c);
std::cout << offset << std::endl;
输出:
0
4
8
改变struct member顺序
struct MyStruct {
char c;
int a;
float b;
};
输出:
4
8
0
原理
(size_t) & (((MyStruct*)0)->a)
将表达式从内向外解析,首先给出0地址或者使用nullptr均可,然后强转成结构体指针类型,接着访问成员a,然后取a的地址,由于一开始给出的地址是0地址,所以a的地址便是相对于结构体起始地址的偏移量
参考:
- https://www.youtube.com/watch?v=4p3grlSpWYA&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=45