Finding offset of a structure element in c

后端 未结 6 1015
自闭症患者
自闭症患者 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:26

    To find the offset, this is one way we can go about it.

    struct a{
        struct b
        {
            int i;
            float j;
        }x;
        struct c
        {
            int k;
            float l;
        }y;
    }z;
    
    int main(){
        struct a* foo = &z;
    
        printf("%d\n", foo);                  //address of z
        printf("%d\n", &(foo->y));            //address of z.y
        printf("%d\n", &( (&(foo->y))->k ));  //address of z.y.k
    
    
        int offset_k = (char*)&( (&(foo->y))->k ) -  (char*)foo ;
        printf("%d\n", offset_k);             
    
        return 0;
    }
    

    Output would be similar to this:

    4225552     //address of z
    4225560     //address of z.y
    4225560     //address of z.y.k
    8           //offset
    
    

    In this particular case, since int i is the first member of the struct, the base address of the struct will be that of int i as well. Otherwise, you could compute the offset of int i in a similar manner.

    int offset_i = (char*)&( (&(foo->x))->i ) -  (char*)foo;  //0 in this case
    
    

    NOTE: The offset will be negative or positive depending on how you define it (if it's with respect to base address or member z.y.k). Here, it is defined to be with respect to base address of struct.

提交回复
热议问题