这段代码产生了下面的奇怪输出.我尝试将字符数组增加到13并打印整个字符串,但最后仍然有奇怪的字符.我在Windows上使用MinGW.这可能是原因吗?
#include <stdio.h>
#include <string.h>
int main() {
char message[10];
int count, i;
strcpy(message, "Hello, world!");
printf("Repeat how many times? ");
scanf("%d", &count);
for(i=0; i < count; i++)
printf("%3d - %s\n", i, message);
if(i==count)
getch();
}
Run Code Online (Sandbox Code Playgroud)

这是因为你必须再给它一个空间,如下所示:
char message[14];
//^^ See here 13 from 'Hello, world!' + 1 to determinate the string with a '\0'
Run Code Online (Sandbox Code Playgroud)
它还必须有空间来保存'\ 0'来确定字符串
也别忘了包括
#include <string.h> //For 'strcpy()'
#include <conio.h> //For 'getch()'
Run Code Online (Sandbox Code Playgroud)
示例输出:
Repeat how many times? 5
0 - Hello, world!
1 - Hello, world!
2 - Hello, world!
3 - Hello, world!
4 - Hello, world!
Run Code Online (Sandbox Code Playgroud)