一、offsetof函数的定义
size_t offsetof(structName,memberName);
引用头文件<stddef.h>
返回结构体中一个成员在该结构体中的偏移量
二、offsetof函数的使用
#include<stdio.h>
#include<stddef.h>
struct S
{
int a;
char b;
int c;
char d;
};
int main()
{
printf("struct S size is %d\n", sizeof(struct S));
printf("a offsetof %u\n", offsetof(struct S, a));
printf("b offsetof %u\n", offsetof(struct S, b));
printf("c offsetof %u\n", offsetof(struct S, c));
printf("d offsetof %u\n", offsetof(struct S, d));
return 0;
}
运行结果如下:
struct S size is 16
a offsetof 0
b offsetof 4
c offsetof 8
d offsetof 12
三、用宏实现offsetof
#define OFFSETOF(structName,memberName)\
(size_t)&(((structName*)0)->memberName)
//用结构体指针为0的地址取出结构体成员,拿到成员的地址,类型转换为size_t
int main()
{
printf("struct S size is %d\n", sizeof(struct S));
printf("a OFFSETOF %u\n", OFFSETOF(struct S, a));
printf("b OFFSETOF %u\n", OFFSETOF(struct S, b));
printf("c OFFSETOF %u\n", OFFSETOF(struct S, c));
printf("d OFFSETOF %u\n", OFFSETOF(struct S, d));
return 0;
}
运行结果如下:
struct S size is 16
a OFFSETOF 0
b OFFSETOF 4
c OFFSETOF 8
d OFFSETOF 12