#include <stdio.h>
struct S
{
char c1;
int i1;
char c2;
};
#define OFFSETOF(a,b) (int)&(((a*)0)->b)
int main()
{
printf("%d\n", OFFSETOF(struct S, c1));
printf("%d\n", OFFSETOF(struct S, i1));
printf("%d\n", OFFSETOF(struct S, c2));
return 0;
}
- ( (struct S*) 0 )->c1 将0转换成struct S类型指针 ,再指向该结构体成员。
- &( ( (struct S*) 0 )->c1 ) 获得结构体成员的地址
- (int) ( &( ( (struct S*)0 )->c1) ) 再转换成int类型得到其成员的偏移量
本文介绍了如何使用宏定义计算C语言结构体成员的偏移量。通过示例代码展示了对结构体`structS`中各成员`c1`、`i1`和`c2`的偏移量的打印,帮助理解内存布局和指针运算。
677

被折叠的 条评论
为什么被折叠?



