您的位置:首页 > 其它

如何算出结构体里的成员变量的偏移量

2007-09-03 12:59 351 查看
有时候 需要知道一个变量在所在结构体中的偏移量,这样只要知道了这个结构体的变量就可以很快得出

这个变量的值。
如何算这个偏移量呢

/*
*This test is how to caculate the offset
*/
struct teststruct{
int b;
char a;
char path[1024];
};
#define aoffset ((unsigned long*)&((struct teststruct*)0) /
->a)

#define pathoffset ((unsigned long)((struct teststruct*)0) /
->path)

/*
*
*
/

int main()
{
printf("a's offset:%d,path's offset:%d/n",aoffset,pathoffset);
/*
*a's offset:4 ,path's offset:5
*/
return 0;
}

|-------|(0)<-----b
| |
| (b) |
|-------|<-----a
| (a) |
|-------|<-----path
| |
| (path)|
| |
| |

这里例子里首先把0地址转换成结构体。那么b的偏移量就是0,a的偏移量就是&a.

还有种方法是把一个知道的地址转换成结构体。这个结构体中的成员变量的地址相对这个地址的差值就是这个成员变量的偏移值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: