前言
我们知道offsetof函数是用来计算结构体中某变量相对于首地址的偏移量的
我们在学习了宏定义后,可以用宏实现该函数功能
具体方法如下
一、offsetof函数的参数
该函数有两个形参
1.structName:需要计算的结构体变量名
2.memberName :结构体内需要计算偏移量的变量
二、实现思路
offsetof函数是用来计算结构体中某变量相对于首地址的偏移量的
struct S
{
int a;
char b;
long c;
};
我们举个例子 如图:
由于偏移量是该变量的首地址和结构体首地址的差值,那我们可以将该结构体地址赋为0,那么该变量的地址就是偏移大小
根据offsetof函数的参数和此规律 我们可以逐步写出宏定义
#define OFFSETOF(stuctName,memberName) (size_t)&((stuctName*)0->memberName)
下面我们来测试一下
#define OFFSETOF(stuctName,memberName) (size_t)&(((stuctName*)0)->memberName)
struct S
{
int a;
char b;
long c;
};
int main()
{
printf("%u\n", OFFSETOF(struct S, a));
printf("%u\n", OFFSETOF(struct S, b));
printf("%u\n", OFFSETOF(struct S, c));
return 0;
}