main()
{
char a[20];
int b;
printf("\n enter your name");
a[20]=getchar();
printf("\n enter your password");
scanf("%d",&b);
if (a=="ilangeeran")
{
printf("\n login successful");
}
}
Run Code Online (Sandbox Code Playgroud)
这是示例程序,在编译此堆栈时发生粉碎错误如何解决此错误?
你的a声明指定了一个包含20个字符的数组:a[0]through到a[19].a[20]超出范围:a[20]=getchar();.
getchar回报int.它这样做是为了区分非字符EOF值和有效字符值.任何正回报值都是一个字符.任何负值都是错误...但您需要将返回值存储在an中int并检查int是否为负值以便处理错误!
int c = getchar();
if (c < 0) {
fputs("Read error while reading from stdin", stderr);
return EXIT_FAILURE;
}
a[19] = c; /* Don't rely on this being a string, since a string is a sequence of
* characters ending at the first '\0' and this doesn't have a '\0'.
* Hence, it isn't a string. Don't pass it to any str* functions! */
Run Code Online (Sandbox Code Playgroud)
同样,您应该可以处理scanf中的错误:
switch (scanf("%d", &b)) {
case 1: /* excellent! 1 means that one variable was successfully assigned a value. */
break;
case 0: fputs("Unexpected input while reading from stdin; "
"The \"%d\" format specifier corresponds to decimal digits.", stderr);
return EXIT_FAILURE;
default: fputs("Read error while reading from stdin", stderr);
return EXIT_FAILURE;
}
Run Code Online (Sandbox Code Playgroud)
if (a=="ilangeeran")是胡说八道.你正在读哪本书?