C/C++ Structure offset

前端 未结 3 1359
自闭症患者
自闭症患者 2020-12-14 15:11

I\'m looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.

IE: given



        
相关标签:
3条回答
  • 2020-12-14 15:22

    How about the standard offsetof() macro (in stddef.h)?

    Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:

    #define OFFSETOF(type, field)    ((unsigned long) &(((type *) 0)->field))
    
    0 讨论(0)
  • 2020-12-14 15:33

    Right, use the offsetof macro, which (at least with GNU CC) is available to both C and C++ code:

    offsetof(struct mstct, myfield2)
    
    0 讨论(0)
  • 2020-12-14 15:38

    printf("offset: %d\n", &((mstct*)0)->myfield2);

    0 讨论(0)
提交回复
热议问题