目录
1.offsetof功能
它是用来求结构体中成员的偏移量的,他是一个宏。
那如果我们想要求一个结构成员的偏移该怎么操作呢,请接着向下看:
#include<stddef.h>
struct peo//定义类型peo
{
int age;
float height;
float weight;
char sex[10];
char id[20];
};
int main()
{
struct peo s1;//定义变量s1
printf("%d ", offsetof(struct peo, age));//求结构中成员的偏移量
printf("%d ", offsetof(struct peo, height));//求结构中成员的偏移量
printf("%d ", offsetof(struct peo, weight));//求结构中成员的偏移量
printf("%d ", offsetof(struct peo, sex));//求结构中成员的偏移量
printf("%d ", offsetof(struct peo, id));//求结构中成员的偏移量
return 0;
}
通过上面的代码我们就可以很好的求出结构成员的偏移了。
2.offsetof的实现
那如果我们想要实现一个跟它一样的宏该如何实现呢?那么让我们来分析一下结构成员的偏移是如何计算的吧?
struct std//用结构定义一个类型
{
int age;
int height;
double weight;
};
int main()
{
return 0;
}
比如上面这个结构怎么来求每个结构成员的偏移量呢?
如果起始地址是从0开始那么,age的偏移是0,height的偏移是4-0,weight的偏移是8-0;
但是结构的地址不会是从0地址处开始的如果我们能够将结构的起始地址转化成零偏移处的地址是不是就能很好的求出结构成员的偏移量了呢!来让我们自己来实现一下宏!
struct std//用结构定义一个类型
{
int age;
int height;
double weight;
};
#define OFFSETOF(type,mName) (size_t)(& (((type*)0)->mName) )//offsetof的实现
int main()
{
struct std s;
printf("%d ", OFFSETOF(struct std, age));
printf("%d ", OFFSETOF(struct std, height));
printf("%d ", OFFSETOF(struct std, weight));
return 0;
}
看到这个代码大家是不是有点不太理解那么接下来让我来为大家剖析一下
看到上面这幅图的分析我相信大家应该对此有了不少理解,如果大家要是觉得我没有表达清楚可以私信问我,或者在评论区留下你的疑问。