-1
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");
    }
}

这是示例程序,在编译时出现此堆栈粉碎错误如何解决此错误?

4

1 回答 1

5

您的 a 声明指定了一个 20 个字符的数组:a[0]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! */

同样,您可能应该处理来自 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;
}

if (a=="ilangeeran")是胡说八道。你在看哪本书?

于 2013-03-29T06:04:53.543 回答