獲取類型大小的變量最好不是 int 類型, 而是 size_t 類型;
size_t 在 stdio.h、stddef.h 都有定義.
1. 獲取已知類型的大小:
#include <stdio.h>
#include <stddef.h>
int main(void)
{
char n = 2;
size_t size;
size = sizeof(char);
printf("%*u: char\n", n,size);
size = sizeof(unsigned char);
printf("%*u: unsigned char\n", n,size);
size = sizeof(short);
printf("%*u: short\n", n,size);
size = sizeof(unsigned short);
printf("%*u: unsigned short\n", n,size);
size = sizeof(int);
printf("%*u: int\n", n,size);
size = sizeof(unsigned);
printf("%*u: unsigned\n", n,size);
size = sizeof(long);
printf("%*u: long\n", n,size);
size = sizeof(unsigned long);
printf("%*u: unsigned long\n", n,size);
size = sizeof(long long);
printf("%*u: long long\n", n,size);
size = sizeof(unsigned long long);
printf("%*u: unsigned long long\n", n,size);
size = sizeof(float);
printf("%*u: float\n", n,size);
size = sizeof(double);
printf("%*u: double\n", n,size);
size = sizeof(long double);
printf("%*u: long double\n", n,size);
size = sizeof(wchar_t);
printf("%*u: wchar_t\n", n,size);
getchar();
return 0;
}
2. 獲取類型大小可根據類型名, 也可根據變量名:
#include <stdio.h>
int main(void)
{
int i;
double d;
printf("%u, %u\n", sizeof(i), sizeof(int));
printf("%u, %u\n", sizeof(d), sizeof(double));
getchar();
return 0;
}
3. 對變量名(非類型名), sizeof 也可以不要括號:
#include <stdio.h>
int main(void)
{
int i;
double d;
printf("%u\n", sizeof i);
printf("%u\n", sizeof d);
getchar();
return 0;
}
4. sizeof(數組變量) 獲取的是數組大小(而非維數), 這和 Delphi 很不一樣:
#include <stdio.h>
int main(void)
{
int nums[10];
printf("%u\n", sizeof nums); /* 數組大小 */
printf("%u\n", sizeof(nums) / sizeof(int)); /* 數組維數 */
getchar();
return 0;
}
返回“學點C語言 - 目錄”