为什么会这样? (即如何将 int
传递给 printf()
结果打印字符串)
#include<stdio.h>
int main() {
int n="String";
printf("%s",n);
return 0;
}
warning: initialization makes integer from pointer without a cast [enabled by default]
int n="String";
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("%s",n);
输出:字符串
编译器:gcc 4.8.5
最佳答案
在你的代码中,
int n="String"; //conversion of pointer to integer
高度依赖于注释1
和
printf("%s",n); //passing incompatible type of argument
调用 undefined behavior . 注释 2 不要那样做。
故事的寓意:警告是有原因的,请注意它们。
注1:
引用 C11
,章节 §6.3.2.3
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. [....]
注2:
§7.21.6.1 章
[....] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
%s
格式说明符的参数类型与 printf()
s
If nol
length modifier is present, the argument shall be a pointer to the initial element of an array of character type. [...]
关于c - 将字符串分配给 int 并将该 int 传递给 printf 如何正确打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917658/