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

标签 c

根据我的知识和一些线索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/

相关文章:

c - int如何转换为char,char如何转换为int?

c - 如何从动态库中检测主要可执行文件的函数定义 - 特别是 malloc

c - sockaddr_storage 究竟是如何工作的?

c - 在此函数中使用未初始化的二维数组

c++ - 原始套接字中的连接功能?

c - 引用结构成员的宏,自行开发的复杂类型到标准 C99 复杂类型的转换

c - 这个结构叫什么?简单的 SoA?

c - 如何在 UNIX 上的 udp 套接字上获取 icmp

c - 与进程树中的兄弟共享PID

c - 在Linux中创建pthread时检测到堆栈崩溃