c - uint16_t 与 printf 的值差异

标签 c gcc printf scanf

以下程序的输出令人困惑。

uint16_t        first = 10, second = 20, third = 30;
// printf("%p\n", &first);
scanf("%d", &second);       // "%d" used intentionally.
printf("%" SCNu16 " ", first);
printf("%" SCNu16 " ", second);
printf("%" SCNu16 "\n", third);

随着第一个 printf 评论,我得到 10 20 0。 (scanf 中的 "%d" 可能会导致此问题。如果我使用 "%"SCNu16 代替 ,效果很好%d)。

当第一个 printf 取消注释时,我得到 0 20 30。 令人困惑的是 - 为什么 printf 会导致输出差异?这是一贯的行为。

最佳答案

在您的代码中,

 scanf("%d", &second); 

是未定义的行为。 %d 期望参数是指向有符号整数类型 (int) 的指针。

引用 C11,第 §7.21.6.2 章,fscanf 函数

[...] Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

也就是说,SCNuN 宏适用于 fscanf 系列,fprintf() 系列的对应项为 PRIuN

关于c - uint16_t 与 printf 的值差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51302699/

相关文章:

c - Mac 上 C 中的段错误,直接从教程中复制

c - C 中的快速交错操作?

gcc - 静态链接Linux中共享对象的依赖关系

c - 如何将格式化数据存储到 C 中的数组?

c - PIC 打印垃圾字符而不是预期字符

c - 使用三元运算符返回 bool 值

c++ - Visual Studio 中的 gcc -Wall -pedantic -Wextra

c++ - 如何将 C 函数导入到尚未在 C 头文件中声明的 C++ 项目中?

python - 如何打印变量之间的空格?

c - 在取消引用 void 指针后转换为 int 是否正确?