C - Find the size of structure

后端 未结 7 988
再見小時候
再見小時候 2021-02-10 01:43

I was asked this as interview question. Couldn\'t answer.

Write a C program to find size of structure without using the sizeof operator.

7条回答
  •  无人共我
    2021-02-10 02:04

    For people that like C macro style coding, here is my take on this:

    #define SIZE_OF_STRUCT(mystruct)     \
       ({ struct nested_##mystruct {     \
             struct mystruct s;          \
             char end[0];                \
          } __attribute__((packed)) var; \
          var.end - (char *)&var; })
    
    void main()
    {
       struct mystruct {
          int c;
       };
    
       printf("size %d\n", SIZE_OF_STRUCT(mystruct));
    }
    

提交回复
热议问题