gpt4 book ai didi

c - 如何在 C 中打印 int 的大小?

转载 作者:太空狗 更新时间:2023-10-29 16:30:17 24 4
gpt4 key购买 nike

我正在尝试在 RHEL 5.6 64 位上编译以下内容,但我不断收到警告

"var.c:7: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long unsigned int’"

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
unsigned int n =10;
printf("The size of integer is %d\n", sizeof(n));
}

如果我将“n”的声明更改为以下并不重要

  1. signed int n =10;
  2. int n = 10;

我想做的就是在我的机器上打印整数的大小,而不是真正查看 limits.h。

最佳答案

sizeof 函数返回一个size_t 类型。尝试使用 %zu 作为转换说明符而不是 %d

printf("The size of integer is %zu\n", sizeof(n));

澄清一下,如果您的编译器支持 C99,请使用 %zu;否则,或者如果您想要最大的可移植性,打印 size_t 值的最佳方法是将其转换到 unsigned long 并使用 %lu

printf("The size of integer is %lu\n", (unsigned long)sizeof(n));

原因是 size_t 被标准保证为无符号类型;然而,该标准并未指定它必须具有任何特定大小(只是大到足以代表任何对象的大小)。事实上,如果 unsigned long 不能代表您的环境的最大对象,您甚至可能需要使用 unsigned long long 转换和 %llu 说明符。

在 C99 中,添加了 z 长度修饰符以提供一种方法来指定打印的值是 size_t 类型的大小。通过使用 %zu,您表示打印的值是 size_t 大小的无符号值。

这是您似乎不必考虑的事情之一,但您确实需要考虑。

进一步阅读:

关于c - 如何在 C 中打印 int 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5943840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com