c - 是什么导致了 c 中 printf 命令的这种奇怪输出,我该如何阻止它发生?

标签 c

此代码会产生以下奇怪的输出。我尝试将字符数组增加到 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();
}

enter image description here

最佳答案

这是因为你必须给它多一个空间,像这样:

char message[14];
           //^^ See here 13 from 'Hello, world!' + 1 to determinate the string with a '\0'

它还必须有空间来保存一个'\0'来确定字符串

别忘了包含

#include <string.h>  //For 'strcpy()'
#include <conio.h>   //For 'getch()'

示例输出:

Repeat how many times? 5
  0 - Hello, world!
  1 - Hello, world!
  2 - Hello, world!
  3 - Hello, world!
  4 - Hello, world!

关于c - 是什么导致了 c 中 printf 命令的这种奇怪输出,我该如何阻止它发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775055/

相关文章:

c - memset 将一些元素设置为 *almost* 零或 nan

c - 对于函数指针 "fptr",为什么 "fptr"和*fptr的值相同?*fptr到底是什么意思?我只知道(*fptr)()或fptr()

c - snprintf 困惑

c - 尝试交换用户输入数组中的多个值

c - 斐波那契一号递归调用

c - 有没有办法让 printf 只引用一个变量的一个实例,用于相同的转换字符重复 x 次?

c - printf 的输出乱序

c - 信号量似乎无法在多线程中正常工作

C 中的计算单元转换器

c - 内核土地套接字连接超时