1. 计算结构体内部数据成员的偏移量
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stddef.h> //包含offsetof()函数
struct teacher
{
char a;
int b;
}
// 计算b的偏移量
void test01()
{
struct teacher t1 = {'a',10};
struct teacher *p = &t1;
//b的偏移量 = b的地址-a的地址
printf("b的偏移量:%d\n", (int)&(p->b) - (int)p);
printf("b的偏移量:%d\n", offsetof(struct teacher, b));
}
2. 通过偏移量 获取结构体内部成员数据
void test02()
{
struct teacher t1 = {'a',10};
printf("t1.b的值为:%d\n", *(int *)((char *)&t1 + offsetof(struct teacher, b));
printf("t1.b的值为:%d\n", *(int *)((int *)&t1 + 1));
}