Finding offset of a structure element in c

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

    As already suggested, you should use the offsetof() macro from , which yields the offset as a size_t value.

    For example:

    #include 
    #include 
    #include "struct_a.h"  /* Header defining the structure in the question */
    
    int main(void)
    {
        size_t off_k_y = offsetof(struct c, k);
        size_t off_k_z = offsetof(struct a, y.k);
        size_t off_i_x = offsetof(struct b, i);
        size_t off_i_z = offsetof(struct a, x.i);
    
        printf("k = %zu %zu; i = %zu %zu\n", off_k_y, off_k_z, off_i_x, off_i_z);
        return 0;
    }
    

    Example output:

    k = 0 8; i = 0 0
    

提交回复
热议问题