gpt4 book ai didi

c - 在 C 语言中,为什么 %s 没有赋值就工作?

转载 作者:太空狗 更新时间:2023-10-29 15:44:56 24 4
gpt4 key购买 nike

根据我的知识和一些线索like this ,如果你想在 C 中打印字符串,你必须这样做:

printf("%s some text", value);

并且将显示该值而不是 %s

我写了这段代码:

char password[] = "default";
printf("Enter name: \n");
scanf("%s", password);
printf("%s is your password", password); // All good - the print is as expected

但我注意到我可以在没有值部分的情况下做完全相同的事情并且它仍然有效:

printf("%s is your password");

所以我的问题是为什么 %s 占位符没有我给它一个值,它怎么知道要给它什么值?

最佳答案

这是未定义的行为,任何事情都可能发生,包括看起来正确的事情。但它是不正确的。如果您使用正确的选项,您的编译器可能会告诉您问题所在。

标准说(强调是我的):

7.21.6.1 The fprintf function

  1. The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered.

关于c - 在 C 语言中,为什么 %s 没有赋值就工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56717553/

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