学点 C 语言(15): 数据类型 - sizeof(检测类型大小)

180it 2020-03-05 AM 2183℃ 0条

学点 C 语言(15): 数据类型 - sizeof(检测类型大小)

获取类型大小的变量最好不是 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;

}

  1. 获取类型大小可根据类型名, 也可根据变量名:

    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;

}

  1. 对变量名(非类型名), sizeof 也可以不要括号:

    include <stdio.h>

int main(void)
{

int i;
double d;

printf("%u\n", sizeof i);
printf("%u\n", sizeof d);

getchar();
return 0;

}

  1. 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;

}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

学点 C 语言(15): 数据类型 - sizeof(检测类型大小)