void test4()
{
struct student {
char a;
int b;
};
struct student stu = {1,1};
struct student* p = &stu;
printf("addr is :%d\r\n", (char*)&(stu.b) - (char*)&(stu.a));
printf("addr is :%d\r\n", (char*)&(p->b) - (char*)&(p->a));
printf("addr is :%d\r\n", (int*)&(p->b) - (int*)&(p->a)); # 这个的输出为1, 需要理解步进的含义
printf("addr is :%d\r\n", (int)&(p->b) - (int)&(p->a));
printf("addr is :%d\r\n", (int)&(p->b) - (int)p);
//printf("addr is :%d\r\n", (void*)&(p->b) - (void*)&(p->a)); #这个会提示类型未定义.
printf("addr is :%d\r\n", offsetof(struct student,b)); #借助 <stddef.h>
}
通过手动的方式去计算, 结构体成员在结构体中的偏移量是多少, 推荐使用 char* 强转(在没有使用底层的api 时)
void test5()
{
struct person {
char a;
int b;
};
struct student
{
char a;
int b;
struct person p;
};
struct student stu = { 1,2,2,3 };
int offset1 = offsetof(struct student, p);
int offset2 = offsetof(struct person, b);
printf("%d\r\n", *(int*)((char*)&stu+offset1+offset2));
printf("%d\r\n", ((struct person*)((char*)&stu + offset1))->b);
}