在 Linux 系统中,offsetof 宏用于计算结构体成员在内存中的偏移量
offsetof 宏的定义如下:
#define offsetof(type, member) ((size_t)&((type *)0)->member)
其中,type 是结构体类型,member 是结构体中的成员变量。这个宏通过将一个指向结构体的空指针((type *)0)转换为一个指向该成员变量的指针,然后获取该指针的值,从而得到该成员相对于结构体起始地址的偏移量。
例如,假设有以下结构体定义:
struct Student {
int id;
char name[20];
float score;
};
要计算 name 成员相对于结构体起始地址的偏移量,可以使用 offsetof 宏:
size_t name_offset = offsetof(struct Student, name);
这样,name_offset 就是 name 成员在结构体中的偏移量。