为什么strlen在C中导致分段错误?

时间:2016-12-03 13:09:23

标签: c segmentation-fault c-strings

(警告)是的,这是我正在进行的任务的一部分,但我现在完全绝望,不,我不是在寻找你们为我解决它,但任何提示都会非常感激! (/警告)

我正在尝试创建一个交互式菜单,用户想要输入一个表达式(例如“5 3 +”),程序应该检测到它是后缀表示法,不幸的是我一直在收到分段错误错误我怀疑它们与使用 strlen 函数有关。

  

编辑:我能够让它工作,首先是char expression[25] = {NULL};行   变为char expression[25] = {'\0'};

     

在调用determine_notation函数时,我从数组中删除了[25],如下所示:   determine_notation(expression, expr_length);

     

此外,input[length]部分我更改为input[length-2],因为之前的评论中提到过input[length] == '\0'input[length--] == '\n'

     

总而言之,感谢所有的帮助!

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int determine_notation(char input[25], int length);

int main(void)
{
    char expression[25] = {NULL}; // Initializing character array to NULL
    int notation;
    int expr_length;

    printf("Please enter your expression to detect and convert it's notation: ");
    fgets( expression, 25, stdin );

    expr_length = strlen(expression[25]); // Determining size of array input until the NULL terminator
    notation = determine_notation( expression[25], expr_length ); 
    printf("%d\n", notation);
}

int determine_notation(char input[25], int length) // Determines notation
{

    if(isdigit(input[0]) == 0)
    {
        printf("This is a prefix expression\n");
        return 0;
    }
    else if(isdigit(input[length]) == 0)
    {
        printf("This is a postfix expression\n");
        return 1;
    }
    else
    {
        printf("This is an infix expression\n");
        return 2;
    }
}

0 个答案:

没有答案