Finding offset of a structure element in c

后端 未结 6 1012
自闭症患者
自闭症患者 2020-12-03 09:46
struct a
{
    struct b
    {
        int i;
        float j;
    }x;
    struct c
    {
        int k;  
        float l;
    }y;
}z;

Can anybody

6条回答
  •  一向
    一向 (楼主)
    2020-12-03 10:27

    struct a foo;
    printf("offset of k is %d\n", (char *)&foo.y.k - (char *)&foo);    
    printf("offset of i is %d\n", (char *)&foo.x.i - (char *)&foo);
    

    foo.x.i refers to the field i in the struct x in the struct foo. &foo.x.i gives you the address of the field foo.x.i. Similarly, &foo.y.k gives you the address of foo.y.k; &foo gives you the address of the struct foo.

    Subtracting the address of foo from the address of foo.x.i gives you the offset from foo to foo.x.i.

    As Gangadhar says, you can use the offsetof() macro rather than the pointer arithmetic I gave. But it's good to understand the pointer arithmetic first.

提交回复
热议问题