gpt4 book ai didi

c - 为什么在scanf的转换说明符中可以嵌入空字符?

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

也许我误解了我的结果,但是:

#include <stdio.h>

int
main(void)
{
char buf[32] = "";
int x;
x = scanf("%31[^\0]", buf);
printf("x = %d, buf=%s", x, buf);
}
$ printf 'foo\n\0bar' | ./a.out
x = 1, buf=foo
由于字符串文字 "%31[^\0]"包含嵌入的null,因此似乎应该将其与 "%31[^"相同,并且编译器应提示 [不匹配。确实,如果您替换字符串文字,那么clang会给出: warning: no closing ']' for '%[' in scanf format string [-Wformat]为什么在传递给scanf的字符串文字中嵌入空字符会起作用吗?
- 编辑 -
以上是未定义的行为,仅发生在“工作”上。

最佳答案

首先是Clang totally fails to output any meaningful diagnostics here,而GCC knows exactly what is happening-同样是GCC 1-0 Clang。
至于格式字符串-很好,它不起作用。 scanf的format参数是一个字符串。该字符串以null结尾,即您给scanf的格式字符串为

scanf("%31[^", buf);
在我的计算机上,编译程序可以
% gcc scanf.c
scanf.c: In function ‘main’:
scanf.c:8:20: warning: no closing ‘]’ for ‘%[’ format [-Wformat=]
8 | x = scanf("%31[^\0]", buf);
| ^
scanf.c:8:21: warning: embedded ‘\0’ in format [-Wformat-contains-nul]
8 | x = scanf("%31[^\0]", buf);
| ^~
扫描集的右括号必须为 ],否则转换说明符无效。如果转换说明符无效,则行为未定义。
而且,在我运行它的计算机上,
% printf 'foo\n\0bar' | ./a.out
x = 0, buf=
Q.E.D.

关于c - 为什么在scanf的转换说明符中可以嵌入空字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66013007/

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