如何算出结构体里的成员变量的偏移量
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.
还有种方法是把一个知道的地址转换成结构体。这个结构体中的成员变量的地址相对这个地址的差值就是这个成员变量的偏移值。
这个变量的值。
如何算这个偏移量呢
/*
*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.
还有种方法是把一个知道的地址转换成结构体。这个结构体中的成员变量的地址相对这个地址的差值就是这个成员变量的偏移值。
相关文章推荐
- 如何求出结构体的成员变量的偏移量
- 结构体(或者联合体)变量的成员在内存里是如何分布的
- 如何通过一个结构体成员变量的地址找到该结构体的首地址?[备忘]
- 【原创】如何由结构体成员的地址逆算出结构体首地址
- 结构体成员变量偏移量的三种解法以及 用宏对成员变量进行修改
- 把“0”强制转化为结构体指针类型得到成员变量的偏移量
- 结构体中成员变量偏移量
- 结构体、类的成员变量、成员函数是如何分配内存的?
- 如何通过一个结构体成员变量的地址找到该结构体的首地址?
- 如何通过一个结构体成员变量的地址找到该结构体的首地址
- 如何通过结构体成员的地址获取结构体变量的地址?
- 如何求出C语言结构体中各个成员的大小及内存偏移量
- 如何取得结构体成员相对于结构体的偏移量
- 如何通过offsetof 动态的给结构体或者类成员变量赋值
- java中的反射机制,以及如何通过反射获取一个类的构造方法 ,成员变量,方法,详细。。
- string 作为结构体成员变量之内存泄露
- 结构体指针初始化以及结构体中成员变量是指针的初始化
- 结构体变量成员的引用(两种方式)
- 深入理解C语言结构体成员变量内存分配
- 如何理解成员变量在堆内,局部变量在栈内?