【发布时间】:2019-10-04 02:57:15
【问题描述】:
我在这段代码中遇到了一些我无法理解的奇怪行为:
char strings[5][4];
for (int i = 0; i < 5; ++i) {
scanf("%s", strings[i]);
}
for (int i = 0; i < 5; ++i) {
printf("%s\n", strings[i]);
}
如果我输入 5 个字符串,例如:
this
is
a
test
help
我在第二个 for 循环中得到了这样的结果:
thisis
is
a
testhelp
help
知道发生了什么吗?快把我逼疯了
【问题讨论】:
-
对不起,我没提:数组的结构是这样的:char strings[5][4];
-
字符串太短,无法正确写入空字符。
-
我不明白你在说什么?如果我完全填写每个字符串,它们的行为会更加奇怪,例如,如果我给它 ["test", "fake", "core", "bird", "town"] 它会给我 ["testfakecorebirdtown", " fakecorebirdtown”, “corebirdtown” “corebird”, “城镇”]
-
需要是字符串[5][5],因为您还需要保存空字符。 C 在遇到空字符时终止字符串。
-
scanf 允许限制字符串中的最大字符数
%4s将适合char[5]
标签: c