网上看到的代码,定义的数组可以输入20个内容,但实际上却可以输入任意字符,这是为何?
#include<stdio.h>
int main (void)
{
char name[20];
scanf("%s", &name, 10);
printf("%s",name);
return 0;
}
网上看到的代码,定义的数组可以输入20个内容,但实际上却可以输入任意字符,这是为何?
#include<stdio.h>
int main (void)
{
char name[20];
scanf("%s", &name, 10);
printf("%s",name);
return 0;
}
scanf 并不会检查缓冲区的长度,你传递给 scanf 的参数 10,并不会用来限制输入。如果输入超过内存大小,会产生覆盖其它内容的严重后果。
所以新标准有了 scanf_s 这个函数,是安全的 scanf,可以用来指定缓冲区大小。