C 语言宏 offsetof 用于返回结构体成员相对结构体开头的字节偏移量。
定义
#define offsetof(type, member) ...offsetof 是 <stddef.h> 中的宏,展开为结构体成员相对结构体开头的字节偏移量(size_t)。
用法
#include <stdio.h>
#include <stddef.h>
struct Point { int x; int y; };
int main() {
printf("x 的偏移: %zu\n", offsetof(struct Point, x));
printf("y 的偏移: %zu\n", offsetof(struct Point, y));
return 0;
}输出:
x 的偏移: 0
y 的偏移: 4注意事项
offsetof 常用于底层编程、容器实现(如 Linux 内核的 container_of 宏)。