Finding offset of a structure element in c

后端 未结 6 1005
自闭症患者
自闭症患者 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条回答
  •  -上瘾入骨i
    2020-12-03 10:27

    Use offsetof() to find the offset from the start of z or from the start of x.

    offsetof() - offset of a structure member

    SYNOPSIS

       #include 
    
       size_t offsetof(type, member);
    

    offsetof() returns the offset of the field member from the start of the structure type.

    EXAMPLE

       #include 
       #include 
       #include 
    
       int
       main(void)
       {
           struct s {
               int i;
               char c;
               double d;
               char a[];
           };
    
           /* Output is compiler dependent */
    
           printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
                   (long) offsetof(struct s, i),
                   (long) offsetof(struct s, c),
                   (long) offsetof(struct s, d),
                   (long) offsetof(struct s, a));
           printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
    
           exit(EXIT_SUCCESS);
       }
    

    You will get the following output on a Linux, if you compile with GCC:

           offsets: i=0; c=4; d=8 a=16
           sizeof(struct s)=16
    

提交回复
热议问题