就是这个代码,只要输入的字符数量超过9,程序就自动关了。
#include
int main(void)
{
char name[10];
char name2[100];
char* c;
c = fgets(name,9,stdin);
// printf("%s%s",name,c);
getchar();
getchar();
getchar();
return 0;
}
不是越界。。。fgets本来就比gets安全,有输入长度限定。你的退出是因为后面getchar()都获取到了字符,程序是正常return,退出的
你name长度只有10个字符,越界了
name 的定义只有 10 个字符,按字符串来处理的话,只能输入 9 个字符 + 一个字符串结束符 NULL。否则,输入过长时,操作越界。
请大家问问题或者回答问题之前仔细看API文档。
在Windows平台上,MSDN对fgets()函数解释如下:
The fgets function reads a string from the input stream argument and stores it in str. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in str is appended with a null character. The newline character, if read, is included in the string.
针对楼主的情况, 以输入1234567890\n为例, fgets(name,9,stdin)会读取(9-1=8)个字符,这样标准输入流还剩下“90\n"共3个字节,正好被后面三个getchar()读取完,程序也就运行到了return, 正常退出。