[英]How can you find the size of a datatype without creating a variable or pointer, or using sizeof of the datatype?
[英]How to find the size of a variable without using 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);
我希望下面的代碼可以在不使用 sizeof() 運算符的情況下解決您在 C++ 中的問題
對於任何變量,如(int、char、float、double、char、short 等等...)
這里我取整數,
int a;
然后將其顯示為字節可尋址輸出,
cout<<(char *)(&a + 1) - (char *)(&a);
這應該有效。
#define xsizeof(x) (char *)(&x+1) - (char *)&x
#define GET_SIZE(myvar) ((char)( ((char*)(&myvar+1) )- ((char*)&myvar) ))
這應該給你變量的大小
#define mySizeof(type) ((uint)((type *)0+1))
在不使用sizeof
運算符的情況下查找變量大小的程序
#include<stdio.h>
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;
}
試試這個,
#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
下面的語句將給出通用的解決方案:
printf("%li\n", (void *)(&i + 1) - (void *)(&i));
i
是一個變量名,可以是任何數據類型(char、short、int、float、double、struct)。
#include<stdio.h>
#include<conio.h>
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.