如何找到一个变量使用的sizeof出大小 [英] How to find the size of a variable with out using sizeof
问题描述
让我们假设我已经声明的变量某些数据类型的'我'(可能是int,char和float或double)...
Let us assume I have declared the variable 'i' of certain datatype (might be int, char, float or double) ...
注意:简单地认为我是声明,不要打扰,如果它是一个int或char或浮动或双数据类型。因为我希望有一个通用的解决方案,我只是提的是可变的我可以是数据类型,即整型,焦炭,float或double。
NOTE: Simply consider that 'i' is declared and dont bother if it is an int or char or float or double datatype. Since I want a generic solution I am simply mentioning that variable 'i' can be of any one of the datatypes namely int, char, float or double.
现在我可以找到变量'我'的大小而不sizeof操作符?
Now can I find the size of the variable 'i' without sizeof operator?
推荐答案
您可以使用下面的宏,从的这里:
You can use the following macro, taken from here:
#define sizeof_var( var ) ((size_t)(&(var)+1)-(size_t)(&(var)))
我们的想法是使用指针运算((及(VAR)+1)
)以确定变量的偏移,然后减去的原的变量的地址,产生其大小。例如,如果你有一个 int16_t我
变量位于 0×0002
,你会被减去 0×0002
从 0x0006
,从而获得为0x4
或4个字节。
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.
不过,我真的没有看到一个有效的理由不使用的sizeof
,但我敢肯定,你必须有一个。
However, I don't really see a valid reason not to use sizeof
, but I'm sure you must have one.
这篇关于如何找到一个变量使用的sizeof出大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!