1.** 注意:offsetof不是函数而是一个宏**
2. 
#include
#include
typedef struct Msg //相对于起始偏移位置
{
int a; //0~3
char b; //4
}Msg;
int main()
{
printf("%zd\n", offsetof(struct Msg, a));
printf("%zd\n", offsetof(struct Msg, b));
return 0;
}
结果:a偏移量为0,b偏移量为4(相对于结构体起始位置)

#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#define OFFSETOF(struct_type, name_in) (size_t)(&((struct_type*)0)->name_in)
typedef struct Msg //相对于起始偏移位置
{
int a; //0~3
char b; //4
}Msg;
int main()
{
printf("%zd\n", offsetof(struct Msg, a));
printf("%zd\n", offsetof(struct Msg, b));
printf("%d\n", OFFSETOF(struct Msg, a));
printf("%d\n", OFFSETOF(struct Msg, b));
}
结果:可以看出OFFSETOF宏模拟实现成功

struct_type是结构体类型名,name_in是成员名。具体操作方法是:
1、先将0转换为一个结构体类型的指针,相当于某个结构体的首地址是0。此时,每一个成员的偏移量就成了相对0的偏移量,这样就不需要减去首地址了。
2、对该指针用->访问其成员,并取出地址,由于结构体起始地址为0,此时成员偏移量直接相当于对0的偏移量,所以得到的值直接就是对首地址的偏移量。
3、取出该成员的地址,强转成size_t并打印,就求出了这个偏移量。
小编制作不易,如果对大家有帮助,请点一个小小的赞哦,谢谢兄弟们!