Finding offset of a structure element in c

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

    It's been 3 years since the question has been asked, I'm adding my answer for the sake of completeness.

    The hacky way of getting the offset of a struct member goes like this

    printf("%p\n", (void*)(&((struct s *)NULL)->i));
    

    It doesn't look pretty, I can't think of anything in pure C (which can get you the offset of the member, without knowing anything else about the structure. I believe the offsetof macro is defined in this fashion.

    For reference, this technique is used in the linux kernel, check out the container_of macro :

    http://lxr.free-electrons.com/source/scripts/kconfig/list.h#L18

    A more elaborate explanation can be found in this article:

    http://radek.io/2012/11/10/magical-container_of-macro/

提交回复
热议问题