【问题标题】:Why the arguments to the format specifiers are not getting printed properly? [closed]为什么格式说明符的参数没有正确打印? [关闭]
【发布时间】:2016-12-08 06:32:02
【问题描述】:

我正在学习 C,但由于某种原因,我的 %s 没有打印出应有的内容。它只是随机字符,%d 总是打印一个类似于 4600688 的数字,而不是我设置的 12:

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

int main()
{
    printf("why is %s happening to me"), "this";
    return 0;
}

这会导致:

为什么PE会发生在我身上

(以及return 文本)。

这是编译器错误还是如何解决?

【问题讨论】:

  • ..什么是“PE”?

标签: c syntax printf format-specifiers


【解决方案1】:

在您的代码中

 printf("why is %s happening to me"), "this";

应该是

 printf("why is %s happening to me", "this");

否则,您将调用undefined behavior,因为缺少为%s 转换说明符提供所需的参数,正如printf() 函数签名所要求的那样。

引用C11,第 7.21.6.3 章

#include <stdio.h>
int printf(const char * restrict format, ...);

printf 函数等效于 fprintf 插入参数 stdoutprintf 的参数之前。

并且,从 §7.21.6.1 开始,“fprintf 函数”(强调我的

fprintf函数将输出写入stream指向的流,受控制 format 指向的字符串,它指定后续参数的方式 转换为输出。如果格式的参数不足,则行为是 未定义。


也就是说,这编译得很好,因为 语法 是有效的,这要感谢(或责备comma-operator

【讨论】:

    猜你喜欢
    • 2013-12-30
    • 2023-03-20
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2018-06-06
    相关资源
    最近更新 更多