当输入大于9时,为什么这个程序会崩溃?

时间:2016-08-03 00:38:58

标签: c

我不知道为什么这会在我的机器上崩溃,但它确实

您将获得一个正整数N,:

如果1 <= N <= 9,则打印它的英文表示。那是&#34;一个&#34; 1,&#34; 2&#34;为2,依此类推。 否则打印&#34;大于9&#34; (没有引号)。 输入格式:

输入只包含一个整数,N。

#include <stdio.h>

const char* itos2(int);

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
   int a;
   scanf("%i", &a );
   printf("%s",((a >= 1 || a <= 9) ? itos2(a) : "Greater than 9"));

   //printf("%s",itos2(a)); this doesn't crash provided a default label is set
   return 0;
}

const char* itos2(int a)
{
const char* str [] = { "one" , "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    switch(a)
    {
        case 1 : return str[0];
        case 2 : return str[1];
        case 3 : return str[2];
        case 4 : return str[3];
        case 5 : return str[4];
        case 6 : return str[5];
        case 7 : return str[6];
        case 8 : return str[7];
        case 9 : return str[8];
        default: return "Greater than 9";
    }
}

2 个答案:

答案 0 :(得分:4)

条件a >= 1 || a <= 9始终为真,这意味着无论您输入的内容为itos2,始终都会调用a。如果a超出[1, 9]范围,则函数itos2将无法返回任何内容,从而产生未定义的行为(在您的情况下崩溃)。

显然你的意思是a >= 1 && a <= 9作为调用itos2的条件。 &&,而非||

答案 1 :(得分:0)

这是您的代码,改进了:

#include <stdio.h>

const char* itos2(int);

// A proper C function prototype
int main(void)
{ 
   int a;

   // Checking the return value of scanf is *required*!
   // If it doesn't return a value which is equal to the number of expected
   // assignments, then your variables are left unassigned, leading to 
   // Undefined Behavior!
   if (scanf("%i", &a) != 1) {
       fprintf(stderr, "Invalid input\n");
       return 1;
   }

   // It's usually better practice to not have to worry about a valid range
   // of inputs when calling a function. Let this function worry about the
   // input checking.
   printf("%s", itos2(a));

   return 0;
}

const char* itos2(int a)
{
    const char* str [] = {
        "zero",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
    };

    // Check boundary conditions. Checking just one boundary case and 
    // returning is simpler and less error-prone than your previous code.
    if (a < 0)
        return "Less than zero";
    if (a > 9)
        return "Greater than nine";

    // Why bother with a switch/case statement when you can simply
    // use the input value to index directly into an array of the strings?
    return str[a];
}

假设您正在使用GCC,始终使用编译至少这组选项:

gcc -Wall -Werror ...