gpt4 book ai didi

c - &string_name 或 string_name for %s 在 C 中打印字符串

转载 作者:行者123 更新时间:2023-12-03 23:06:14 25 4
gpt4 key购买 nike

如果我在 C 中有以下字符串:

char s[]="Question";

然后我注意到下面的两个 prtintf 都在终端中正确打印了字符串。

1.

printf("%s\n",s);

2.

printf("%s\n",&s);

哪种是在 C 中打印字符串的正确方法。如果两者相同,那么遵循的约定是什么? 1 还是 2?

谢谢。

最佳答案

char s[]="Question";
printf("%s\n",&s);

是未定义的行为,因为,

§7.21.6.1/8 The conversion specifiers and their meanings are:

[...]

s          If no l length modifier is present, the argument shall be a pointer to the initial element of             an array of character type.

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

在此上下文中的

s 将衰减为指针类型。由于 & 产生一个指针,因此您传递给 printf 的类型实际上是一个指向指针的指针。

关于c - &string_name 或 string_name for %s 在 C 中打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28401760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com