c++ - C 语言 gets() 和 printf() 的问题

浏览:31日期:2023-05-18

问题描述

当我输入一串字符

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.0123456789Abort trap: 6

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

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

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

问题解答

回答1:

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

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

相关文章: