写一个宏,计算结构体某个变量相对于起始位置的偏移量(模拟实现offsetof)
//模拟size_t offsetof(structName, memberName)
#define OFFSETOF(struct_name,mem_name) (int)&(((struct_name*)0) -> mem_name)
struct A
{
int a;
short b;
int c;
char d;
};
int main()
{
printf("%d\n", OFFSETOF(struct A, a));
printf("%d\n", OFFSETOF(struct A, b));
printf("%d\n", OFFSETOF(struct A, c));
printf("%d\n", OFFSETOF(struct A, d));
return 0;
}
本文介绍了一个C语言宏定义,如何使用OFFSET_OF宏来计算结构体中特定成员相对于起始位置的偏移量,通过实例展示了在`structA`中的`a`, `b`, `c`, `d`成员的偏移量计算。
976

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



