计算 int、float、double 和 char 大小的 C 程序
要理解此示例,您应该具备以下 C 语言编程主题的知识:
在本例中,我们使用 sizeof(variable)
操作符计算一个变量的大小。并且,我们还使用了 %lu
or %zu
格式说明符打印由 sizeof
返回的结果。
查找变量大小的程序
#include<stdio.h>
int main() {
int intType;
float floatType;
double doubleType;
char charType;
// sizeof evaluates the size of a variable
printf("Size of int: %zu bytes\n", sizeof(intType));
printf("Size of float: %zu bytes\n", sizeof(floatType));
printf("Size of double: %zu bytes\n", sizeof(doubleType));
printf("Size of char: %zu byte\n", sizeof(charType));
return 0;
}
输出
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
在这个程序中,声明了 4 个变量 intType
, floatType
, doubleType
和 charType
。
然后,使用 sizeof
运算符计算每个变量的大小。