2017-04-05 41 views
1

我有兴趣生成偏移量为结构域的数组。生成偏移量为结构域的数组

struct B 
{ 
    int pig[100]; 
    bool donkey[100]; 
} 

struct A 
{ 
    int ant[100]; 
    bool cat[38]; 
    struct B dog[78]; 
} 

main() 
{ 
    int offset[100+38+78] /* ant offsets + cat offsets + dog offsets */ 
    /* How do I fill up these offset array to fill in with offsets of ant, cat, dog */ 
} 

Output should be something like: 
offset[0] = 0; 
offset[1] = 4; 
...... 
...... 
offset[99]= 4*99; 
....... 
offset[100+38+78-1] = ? ; 

我知道C不支持反射,我们可以在一定程度上使用X_MACROS,但是我的结构非常复杂。我想以这个问题发布的基本简单结构开始。

回答

1

您可以将数组元素的地址转换为char *,然后减去结构的地址。

struct A a; 
for (int i = 0; i < 100; i++) { 
    offset[i] = (char*)&a.ant[i] - (char*)&a; 
} 
for (int i = 0; i < 38; i++) { 
    offset[100 + i] = (char*)&a.cat[i] - (char*)&a; 
} 
for (int i = 0; i < 78; i++) { 
    offset[100 + 38 + i] = (char*)&a.dog[i] - (char*)&a; 
+0

谢谢巴尔玛。这有帮助。只是出了问题,有没有办法通过将结构变量作为参数传递来获取字段的偏移量。例如Input:cat [37]:cat [37]的偏移量是XXXX? – vip

+0

你可以使用'(char *)&a.cat [37] - char(*)&a' – Barmar

+0

再次感谢。有没有一种方法可以获得字段pig [2]相对于结构体A的偏移量,并且根本不使用结构体B信息,比如,offsetof(struct A,pig [2])是? – vip