c - 为什么格式说明符的参数没有正确打印?

标签 c syntax printf format-specifiers

<分区>

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

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

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

这导致:

Why is PE happening to me

(和返回文本)。

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

最佳答案

在你的代码中

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

应该是

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

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

引用 C11,章节 §7.21.6.3

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

The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

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

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined.


这就是说,由于语法 是有效的,这编译得很好,这要归功于(或责备)comma-operator .

关于c - 为什么格式说明符的参数没有正确打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41033164/

相关文章:

c - 桌面环境是一个自定义操作系统

c# - 在 c# 中使用来自 c 源的 cygwin 编译的 dll,在 socket() 、 fork() 和类似的 read write protected memory 上出错

C打印 double 类型指针值不起作用

c++ - 如何使用 C++20 std::format?

使用 printf 跨平台打印 64 位整数

c - 如何用c语言调用pic18F4550中的方法(编译器)

c++ - 如何读取包含 Unicode 内容的文件

javascript - 为什么++[[]][+[]]+[+[]] 返回字符串 "10"?

C函数语法,参数类型在参数列表之后声明

MySQL 语法中的 PHP 错误