首页 > 解决方案 > 有人可以解释一下为什么当“字符串”与“%d” fromat 说明符一起使用时,它会给出奇怪的输出

问题描述

这是程序:

#include <stdio.h>
main()
{
  printf("%d", "A"); // Can i know what the output from "printf" even means why the output is so strange

} // this outputs: "4214884" in my compiler

如您所见,输出是如此奇怪,你们中的任何人都可以向我解释一下。这是未定义的行为吗?这种行为是否在C 标准中的任何地方描述,所以我可以阅读它

标签: cprintfformat-specifiersformat-string

解决方案


是的,这 未定义的行为%d期望参数是一个整数,这里你传递的是字符串文字的第一个元素的地址,它是一个指针类型。

根据第 7.21.6.1/P9C11

[...]如果任何参数不是相应转换规范的正确类型,则行为未定义。

也就是说,对于托管环境,main()应该是int main(void).


推荐阅读