The use of offsetof()
#include<stdio.h>
#include<stddef.h>
struct Person{
char a; //0~3
int b; //4~7
};
void test01()
{
struct Person p1;
struct Person* p = &p1;
printf("b的偏移量为:%d\n",(int)&(p->b)-(int)p);
printf("b的偏移量为:%d\n",offsetof(struct Person,b));
}
//通过偏移量获取到数据
void test02()
{
struct Person p1 = {'a',10};
printf("p.b = %d\n",*(int*)((char*)&p1+offsetof(struct Person,b))); //char* 步长
printf("p.b = %d\n",*(int*)((int*)&p1 + 1));
}
int main()
{
test01();
test02();
return 0;
}
operation result:
The offset of b is: 4
The offset of b is: 4
pb = 10
pb = 10
Please press any key to continue...