C - Find the size of structure

后端 未结 7 984
再見小時候
再見小時候 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 01:49

    Here's two macro versions for the two forms of sizeof (takes a type vs. takes a variable) that you can use for all the code you'll never write where you aren't allowed to use sizeof:

    #define type_sizeof(t) (size_t)((char *)((t *)1024 + 1) - (char *)((t *)1024))
    #define var_sizeof(v)  (size_t)((char *)(&(v) + 1) - (char *)&(v))
    

    Perhaps with some deep magic you can combine the two into a single macro that will almost serve as a drop-in replacement in all this sizeof-less code. (Too bad you can't fix the multiple-evaluation bugs.)

提交回复
热议问题