如何使用sizeof找出变量的大小

让我们假设我已声明某个数据类型的变量’i’(可能是int,char,float或double)…

注意:只需考虑声明’i’,如果它是int或char或float或double数据类型,则不要打扰。 由于我想要一个通用的解决方案,我只是简单地提到变量’i’可以是任何一种数据类型,即int,char,float或double。

现在我可以找到没有sizeof运算符的变量’i’的大小吗?

您可以使用以下宏:

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

我们的想法是使用指针算法( (&(var)+1) )来确定变量的偏移量,然后减去变量的原始地址,从而产生其大小。 例如,如果int16_t i变量位于0x0002 ,则将从0x0006减去0x0002 ,从而获得0x4或4个字节。

但是,我并没有真正看到不使用sizeof的正当理由,但我相信你必须有一个。

自从我编写任何C代码以来已经很久了,我从来都不擅长它,但这看起来是正确的:

 int i = 1; size_t size = (char*)(&i+1)-(char*)(&i); printf("%zi\n", size); 

我相信有人可以告诉我为什么这是错误的,但它为我打印了一个合理的价值。

这有效..

 int main() { int a; //try changing this to char/double/float etc each time// char *p1, *p2; p1 = &a; p2 = (&a) + 1; printf("size of variable is:%d\n", p2 - p1); } 
 int *a, *b,c,d;/* one must remove the declaration of c from here*/ int c=10; a=&c; b=a; a++; d=(int)a-(int)b; printf("size is %d",d); 

试试这个,

 #define sizeof_type( type ) ((size_t)((type*)1000 + 1 )-(size_t)((type*)1000)) 

对于以下用户定义的数据类型,

 struct x { char c; int i; }; sizeof_type(x) = 8 (size_t)((x*)1000 + 1 ) = 1008 (size_t)((x*)1000) = 1000 

这应该给你变量的大小

 #define mySizeof(type) ((uint)((type *)0+1)) 

编程以查找变量的大小而不使用sizeof运算符

 #include int main() { int *p,*q; int no; p=&no; printf("Address at p=%u\n",p); q=((&no)+1); printf("Address at q=%u\n",q); printf("Size of int 'no': %d Bytes\n",(int)q-(int)p); char *cp,*cq; char ch; cp=&ch; printf("\nAddress at cp=%u\n",cp); cq=cp+1; printf("Address at cq=%u\n",cq); printf("Size of Char=%u Byte\n",(int)cq-(int)cp); float *fp,*fq; float f; fp=&f; printf("\nAddress at fp=%u\n",fp); fq=fp+1; printf("Address at fq=%u\n",fq); printf("Size of Float=%u Bytes\n",(int)fq-(int)fp); return 0; } 
 #include #include struct size1 { int a; char b; float c; }; void main() { struct size1 *sptr=0; //declared one pointer to struct and initialise it to zero// sptr++; printf("size:%d\n",*sptr); getch(); } 

以下声明将给出通用解决方案:

 printf("%li\n", (void *)(&i + 1) - (void *)(&i)); 

i是一个变量名,可以是任何数据类型(char,short,int,float,double,struct)。