c - 将字符串分配给 int 并将该 int 传递给 printf 如何正确打印字符串?

标签 c string int printf

为什么会这样? (即如何将 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 no l 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/

相关文章:

c++ - 尝试一次取 1 个随机数字

Java string[] 部分复制

c - 尝试比较二维数组中的字符串

c++ - 使用 'int' 数据类型时出错,即使数字不是小数

java - 向方法发送动态数量的变量的最佳方法是什么?

c++ - 计算 64 位 int 的百分比

c - 你如何清除 C 中的控制台屏幕?

java - 由于 int 数据赋值中的逻辑错误而打印零值

c - Ansi C 重新评估 Y 坐标

c++ - 如何只用一个#define 定义两个或多个值?