1、offsetof 宏的使用
# 在 stddef.h 中遇到这样奇怪的宏
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)
offsetof() 宏返回结构或联合复合中元素名称的偏移量。这提供了一种可移植的方法来确定偏移量。
宏中的各种运算符按顺序计算,以便执行以下步骤:
((s *)0): 取整数零并将其转换为指向 s 的指针。
((s *)0)->m: 引用指向结构成员 m 的指针。
&(((s *)0)->m):计算 m 的地址。
(size_t)&(((s *)0)->m): 将结果转换为适当的数据类型
eg:
#include <stdio.h>
#include <stddef.h>
int main()
{
struct Demo{
int a;
char b;
double c;
char d[];
};
printf("sizeof(struct Demo)=%ld\n", (long) sizeof(struct Demo));
printf("offsets: a=%ld; b=%ld; c=%ld d=%ld\n",
(long)offsetof(struct Demo, a),
(long)offsetof(struct Demo, b),
(long)offsetof(struct Demo, c),
(long)offsetof(struct Demo, d));
return 0;
}
运行结果:
sizeof(struct Demo)=16
offsets: a=0; b=4; c=8 d=16