c - 当格式说明符不正确时,printf 函数如何在 c 中工作?

标签 c printf format-specifiers

<分区>

在一次采访中,我被问及以下代码片段的输出:

printf("%d", "computer");

我是一个c#开发者,之前也学过C,但是被问到这个问题的时候,我是一头雾水。 当我在 Windows 10 计算机(64 位)中运行相同的问题时,它给出了 putput as

3571712

请说明发生这种情况的原因。

最佳答案

“不起作用”,您观察到的是 undefined behavior 的结果.

引用 C11,章节 §7.21.6.1/p9

[...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

在您的例子中,转换说明符是 %d,它需要一个 int 类型的参数,但您提供的是 char*,并且它们不是兼容类型,因此是 UB。

关于c - 当格式说明符不正确时,printf 函数如何在 c 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780043/

相关文章:

c - Vigenere Cipher 只能在处理 C 中的空格 ("") 之前有效 - 为什么?

c - 为什么使用 "%s"格式说明符 printf 一个字符数组会在数组中的最后一个字符之后输出额外的无意义值?

c - C语言中的二进制数相加

c - gstack.c :14:3: error: unknown type name 'gqdata'

c - snprintf 和字符串数组语法

c - 在 C 中将多维结构体值写入文件

c++ - 如何在 CString::Format 中重复一个字符

c - C中的浮点变量

python - 使用 C 扩展扩展 python

C 什么时候 char** 应该以 null 终止?