字符串在 for 循环中未正确打印,但之前打印正常
string not printing correctly in for loop but printing okay before
我正在出一本学习c的教材。其中一项练习是从字面上复制书中的代码来演示如何使用 scanf。它获取用户输入的内容应该打印多少次。使用 for 循环打印出字符串,字符串的最后一个字符似乎变得混乱了。请参阅下文,如有任何帮助,我们将不胜感激。到目前为止,我已经尝试删除 '\n' 以查看是否是它导致了问题。我已经在循环之前打印出字符串以查看字符串是否有错误,但它似乎在循环外工作正常。代码如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
char message[10];
int count, i;
strcpy(message, "Hello, World!");
printf("Repeat how many times? ");
scanf("%d", &count);
printf("%s\n", message);
for(i = 0; i < count; ++i)
{
printf("%3d - %s\n", i, message);
}
return 0;
}
结果:
Repeat how many times? 3
Hello, World!
0 - Hello, Wor
1 - Hello, Wor
2 - Hello, Wor
提前致谢。
欢迎来到Whosebug
。该站点的名称是您问题的答案。您正在尝试将 14 个字符存储到一个最多可容纳 10 个字符的字符串中。此后发生的一切都是未定义的行为。
什么是未定义行为?
Undefined behaviour is undefined. It may crash your program. It may do
nothing at all. It may do exactly what you expected. It may summon
nasal demons. It may delete all your files. The compiler is free to
emit whatever code it pleases (or none at all) when it encounters
undefined behaviour.
Any instance of undefined behaviour causes the entire program to be
undefined - not just the operation that is undefined, so the compiler
may do whatever it wants to any part of your program. Including time
travel.
我正在出一本学习c的教材。其中一项练习是从字面上复制书中的代码来演示如何使用 scanf。它获取用户输入的内容应该打印多少次。使用 for 循环打印出字符串,字符串的最后一个字符似乎变得混乱了。请参阅下文,如有任何帮助,我们将不胜感激。到目前为止,我已经尝试删除 '\n' 以查看是否是它导致了问题。我已经在循环之前打印出字符串以查看字符串是否有错误,但它似乎在循环外工作正常。代码如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
char message[10];
int count, i;
strcpy(message, "Hello, World!");
printf("Repeat how many times? ");
scanf("%d", &count);
printf("%s\n", message);
for(i = 0; i < count; ++i)
{
printf("%3d - %s\n", i, message);
}
return 0;
}
结果:
Repeat how many times? 3
Hello, World!
0 - Hello, Wor
1 - Hello, Wor
2 - Hello, Wor
提前致谢。
欢迎来到Whosebug
。该站点的名称是您问题的答案。您正在尝试将 14 个字符存储到一个最多可容纳 10 个字符的字符串中。此后发生的一切都是未定义的行为。
什么是未定义行为?
Undefined behaviour is undefined. It may crash your program. It may do nothing at all. It may do exactly what you expected. It may summon nasal demons. It may delete all your files. The compiler is free to emit whatever code it pleases (or none at all) when it encounters undefined behaviour.
Any instance of undefined behaviour causes the entire program to be undefined - not just the operation that is undefined, so the compiler may do whatever it wants to any part of your program. Including time travel.