结构体偏移量

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;
}

运行结果:

b的偏移量为:4
b的偏移量为:4
p.b = 10
p.b = 10
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/weixin_42596333/article/details/104510228