一、需求
假设有以下需求
#include <stdio.h>
typedef struct MyStruct1
{
int a ;
char b ;
int c ;
} Struct;
Struct struct1 = { 1,'B',4 };
// 主函数
int main(int argc, char **argv)
{
// 假设我们只知道 A 的地址,struct1 的地址是不知道的
// 那么如何通过 A 的地址去找到 struct1 的地址呢?
int A = struct1.c;
return 0;
}
能想到其中一种方法就是利用地址的偏移量来完成
接下来,我们利用地址偏移量来提供一种解决方案
代码如下
#include <stdio.h>
typedef struct MyStruct1
{
int a ;
char b ;
int c ;
char d[10];
} Struct;
Struct struct1 = { 99,'B',100, "HHH" };
// 主函数
int main(int argc, char **argv)
{
// 假设我们只知道 A 的地址,连 struct1 的地址都不知道
// 那么如何通过 A 去访问到 a b c呢?
char *A = &struct1.b;
// 找到 A 与结构体首地址的偏差
int offset = (int)&((Struct*)0)->b - (int)&((Struct*)0)->a;
// 地址偏移到结构体首地址
Struct* dst = (Struct*)((char*)A - offset);
// 完成
printf("a=%d\