sizeof 运算符如何在 C 中工作?
How sizeof operator works in C?
在下面的代码中:
#include<stdio.h>
int main(void)
{
printf("%d",sizeof(int));
return 0;
}
在 gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 编译器上编译时给出警告:
format ‘%d’ expects argument of type ‘int’, but argument 2 has type
‘long unsigned int’ [-Wformat=] printf("%d",sizeof(int));
为什么我会收到此警告? return 类型的 sizeof 是 'long unsigned int' 吗?
当我用“%ld”替换“%d”时,警告消失了。
sizeof
operator is processed at compile time (and can be applied on both types and expressions). It gives some constant* of type size_t
. On your system (and mine Debian/Linux/x86-64 also) sizeof(int)
is (size_t)4
. That size_t
type 经常被 typedef
编辑成某种类型,如 unsigned long
(但它实际上是什么整数类型取决于实现)。你可以编码
printf("%d", (int)sizeof(int));
或(因为 printf 理解 %zd
或 %zu
控制格式字符串 size_t
)
printf("%zu", sizeof(int));
为了获得最大的可移植性,使用 %zu
(而不是 %ld
)来打印 size_t
(因为您可能会发现 size_t
是 unsigned int
等...).
注 *:sizeof
始终不变,除了 VLA
在下面的代码中:
#include<stdio.h>
int main(void)
{
printf("%d",sizeof(int));
return 0;
}
在 gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 编译器上编译时给出警告:
format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] printf("%d",sizeof(int));
为什么我会收到此警告? return 类型的 sizeof 是 'long unsigned int' 吗?
当我用“%ld”替换“%d”时,警告消失了。
sizeof
operator is processed at compile time (and can be applied on both types and expressions). It gives some constant* of type size_t
. On your system (and mine Debian/Linux/x86-64 also) sizeof(int)
is (size_t)4
. That size_t
type 经常被 typedef
编辑成某种类型,如 unsigned long
(但它实际上是什么整数类型取决于实现)。你可以编码
printf("%d", (int)sizeof(int));
或(因为 printf 理解 %zd
或 %zu
控制格式字符串 size_t
)
printf("%zu", sizeof(int));
为了获得最大的可移植性,使用 %zu
(而不是 %ld
)来打印 size_t
(因为您可能会发现 size_t
是 unsigned int
等...).
注 *:sizeof
始终不变,除了 VLA