在C语言中,#define宏可以用来定义offsetof宏,用来计算结构体中成员的偏移量。offsetof宏通常定义如下:
#define offsetof(type, member) ((size_t) &((type *)0)->member)使用offsetof宏时,需要传入结构体类型和成员变量名作为参数,如下所示:
#include <stdio.h>#include <stddef.h>struct example { int x; char y; float z;};int main() { size_t offset = offsetof(struct example, y); printf("Offset of member y in struct example is %zu\n", offset); return 0;}运行上面的代码会输出Offset of member y in struct example is 4,表示y成员在struct example结构体中的偏移量为4个字节。


