我正在使用PostFix计算器并且遇到了分段错误

时间:2015-05-10 03:56:54

标签: c

我正在研究一个计算器,当我运行它时,我一直遇到分段错误,但它没有说明从哪里或什么原因导致它,所以我真的不知道如何解决它。我很确定问题在于评估。我是否错误地推动了新值或导致这种情况的原因?

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

struct stack
{
    const char * data;
    struct stack *bottom;
};

struct stack * push(struct stack *stk,const char * x)
{
    struct stack *nstk = (struct stack *)malloc(sizeof(struct stack));

    nstk -> data = x;
    nstk->bottom = stk;

    return nstk;
}


const char * peek(struct stack *stk)
{
    if(stk -> data)
        return stk->data;
    else
        return NULL;
}

struct stack *pop(struct stack *stk)
{
    struct stack *tmp;

    tmp = stk->bottom;
    stk-> bottom = NULL;
    if(stk)
    {
        free(stk);
    }

    return tmp;
}
FILE * input_from_args(int argc,const char *argv[])
{
    if(strcmp(argv[1],"-e") != 0 && strcmp(argv[1],"-c") != 0 && strcmp(argv[1],"-g") != 0)
    {
        printf("Option %s is not supported \n", argv[1]);
        exit(0);
    }

    else
    {
        return stdin;
    }
}
void evaluate(struct stack * equation)
{
    const char * a;
    int num;
    int num2;
    int ans;
    char buf[256];

    while(equation -> bottom)
    {
        num2 = atoi(peek(equation));
        equation = pop(equation);
        num = atoi(peek(equation));
        equation = pop(equation);
        a = peek(equation);
        equation = pop(equation);

        if(strcmp(a,"A") == 0)
        {
            ans = num + num2;
            sprintf(buf,"%i",ans);
            puts(buf);
            equation = push(equation,buf);
        }
        else if(strcmp(a,"X") == 0)
        {
            ans = num * num2;
            sprintf(buf,"%i",ans);
            equation = push(equation,buf);
        }
        else  if(strcmp(a,"D") == 0)
        {
            ans = num / num2;
            sprintf(buf,"%i",ans);
            equation = push(equation,buf);

        }
        else if(strcmp(a,"S") == 0)
        {
            ans = num - num2;
            sprintf(buf,"%i",ans);
            equation = push(equation,buf);
        }
        else if(strcmp(a,"M") == 0)
        {
            ans = num % num2;
            sprintf(buf,"%i",ans);
            equation = push(equation,buf);
        }
    }
}

int main(int argc,const char *argv[])
{
    FILE *src = input_from_args(argc, argv);

    if (src == NULL)
    {
        printf("%s", "Invalid Source");
        exit(EXIT_FAILURE);
    }

    struct stack * equation = NULL;
    equation = (struct stack*)malloc(sizeof(struct stack));

    int i;
    for (i=argc -1; i >= 2; i--)
    {
        equation =  push(equation,argv[i]);
    }

    if(strcmp(argv[1],"-e") == 0)
    {
        evaluate(equation);
    }

    free(equation);

    return EXIT_SUCCESS;
}

0 个答案:

没有答案