gpt4 book ai didi

c - 在 32 和 64 平台上带有 sizeof 的 printf : how do I handle format code in platform independent manner?

转载 作者:太空狗 更新时间:2023-10-29 16:23:05 26 4
gpt4 key购买 nike

我有一些代码可以打印程序使用的内存量。该行与此类似:

printf("The about of RAM used is %u", anIntVariable*sizeof(double) );

其中 anIntVariable 是 double 数组元素数量的 int 变量。无论如何,在 32 位系统上我从未遇到过任何问题,但在 64 位系统上,我收到编译器警告关于将“%u”用于无符号长整数。使用“%lu”作为格式代码修复了 64 位上的问题,但导致编译器在 32 位上报错,因为类型返回到 unsigned int。我发现,确实,sizeof(double) 在 32 位和 64 位系统上返回不同的值。我找到了一些将代码从 32 位转换到 64 位的网页指南,但我宁愿拥有适用于这两种位的代码,而不是仅仅来回转换。

如何以独立于平台的方式编写这一行?我知道有很多方法可以使用预处理器指令来做到这一点,但这似乎是一种 hack。当然有一种我没有意识到的优雅方式。

最佳答案

可移植 printf 标识符在包含文件中提供 inttypes.hhere .

这个包含文件为您的特定运行时提供了许多可移植的标识符。对于您的示例,您需要 PRIuPTR,这意味着“PRintf I标识符u已签名,大小不超过指针的大小”。

您的示例将是:

printf("The amount of RAM used is %" PRIuPTR, anIntVariable*sizeof(double) );

使用 GCC 4.3(int anIntVariable = 1)在 64 位 Linux 上的结果:

$ gcc test.c -m32 -o test && ./test
The amount of RAM used is 8
$ gcc test.c -o test && ./test
The amount of RAM used is 8

为了完整起见,scanf也有标识符,其前缀是SCN。

关于c - 在 32 和 64 平台上带有 sizeof 的 printf : how do I handle format code in platform independent manner?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1403074/

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