How to find the size of a variable without using sizeof

后端 未结 10 1725
终归单人心
终归单人心 2020-12-17 06:07

Let us assume I have declared the variable \'i\' of certain datatype (might be int, char, float or double) ...

NOTE: Simply consider that \'i\' is

10条回答
  •  臣服心动
    2020-12-17 06:30

    You can use the following macro, taken from here:

    #define sizeof_var( var ) ((size_t)(&(var)+1)-(size_t)(&(var))) 
    

    The idea is to use pointer arithmetic ((&(var)+1)) to determine the offset of the variable, and then subtract the original address of the variable, yielding its size. For example, if you have an int16_t i variable located at 0x0002, you would be subtracting 0x0002 from 0x0006, thereby obtaining 0x4 or 4 bytes.

    However, I don't really see a valid reason not to use sizeof, but I'm sure you must have one.

提交回复
热议问题