c++ - C 语言 gets() 和 printf() 的问题
大家讲道理
大家讲道理 2017-04-17 13:25:28
0
1
525

当我输入一串字符

    char str[10];
    printf("Input a string.\n");
    gets(str);
    printf("The string you input is: %s",str);

当我输入的字符串长度大于0 的时候,输出结果是这样的

1ang:lab lang$ ./exercise 
Input a string.
warning: this program uses gets(), which is unsafe.
0123456789
Abort trap: 6

但是我加了 \n, printf("The string you input is: %s\n",str); 输出的结果就不一样了

1ang:lab lang$ ./exercise 
Input a string.
warning: this program uses gets(), which is unsafe.
0123456789
The string you input is: 0123456789
Abort trap: 6

它会先printf然后再报错, 这是为什么?(编译器是GCC)

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

répondre à tous(1)
小葫芦

C 中的字符串使用空字符\0作为结尾,所以在分配数组时需要多分配一个字符的空间。报错是因为你的输入0123456789一共为10个字符,加上结尾自动添加的空字符\0一共11个字符,而你的数组大小只有10,所以越界了。

另外gets函数自11年的标准后已被废除,请使用其他函数,如scanfstd::getlinestd::cin等读入字符串。

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!