现在的位置: 首页 > 综合 > 正文

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

2013年11月23日 ⁄ 综合 ⁄ 共 669字 ⁄ 字号 评论关闭

有时候 需要知道一个变量在所在结构体中的偏移量,这样只要知道了这个结构体的变量就可以很快得出

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

/*
 *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.

还有种方法是把一个知道的地址转换成结构体。这个结构体中的成员变量的地址相对这个地址的差值就是这个成员变量的偏移值。

 

抱歉!评论已关闭.