c - RPN 输出错误数据 : C

标签 c pointers stack rpn

我正在尝试创建一个简单的 RPN 解析器,它只接受单位数字值和 +-*/运算符。我使用堆栈来存储原始输入,但在打印输出时遇到问题。

当我运行调试时,它给出错误消息“程序收到信号 SIGSEGV,段错误。”,与第 94 行相关。在本例中我使用的输入是 11+。我最初认为这与弹出的数据未正确存储有关,因此我创建了 T1 和 T2 作为临时变量。但这并不能解决问题。我还尝试同时取消彼此之间的推送和弹出命令的嵌套;仍然没有成功。

程序在崩溃之前在调试之外运行时会打印似乎是内存地址的内容,因此我检查了指针,但这些对我来说似乎没问题,但我只是在学习,所以我不能确定。提前致谢!

lib.c 文件在这里:

#include "defs.h"
//Initialising the stack
TopStack *initTOS()
{
TopStack *pTopStack;
pTopStack=(TopStack*)malloc(sizeof(TopStack));
return(pTopStack);
}

//Pushing an element onto the stack
void push( TopStack *ts, int val)
{
if(ts->num==0)
{
    Stack *pNewNode;
    pNewNode=(Stack*)malloc(sizeof(Stack));
    pNewNode->val=val;
    pNewNode->next=NULL;
    ts->top=pNewNode;
    ts->num++;
}
else if(ts->num!=0)
{
    Stack *pNewNode;
    pNewNode=(Stack*)malloc(sizeof(Stack));
    pNewNode->val=val;
    pNewNode->next=ts->top;
    ts->top=pNewNode;
    ts->num++;
}
}

int pop(TopStack *ts)
{
if(ts->num==0)
    {
        printf("Can't pop, stack is empty!\n");
        exit(1);
    }
else{
        Stack *pTemp = ts->top;
        int RemovedValue;
        RemovedValue=pTemp->val;
        ts->top=pTemp->next;
        ts->num--;
        free(pTemp);
        return (RemovedValue);
    }
}

void testStack(TopStack *ts)
{
int RemovedValue;
push(ts,1);
push(ts,2);
printf("the popped value was %i\n",pop(ts));
printf("the popped value was %i\n",pop(ts));
}

void parseRPN(TopStack *st)
{
char Input[50];
int i;
do{
    printf("please enter an expression in single-digit integers using RPN:\n");
    scanf("%49s",&Input);
    if (strlen(Input)>=50)
        {
            printf("that expression was too large for the RPN engine to handle! please break it down into smaller sub-tasks.\n");
            fflush(stdin);
            continue;
        }
    break;
}while(true);

for (i=0; Input[i] != '\0';i++)
    {
        if ((isdigit(Input[i])==0) && ((Input[i] != '+') && (Input[i] != '-') && (Input[i] != '*') && (Input[i] != '/')))
        {
            printf("Error: Invalid operand to RPN\nExiting...\n");
            exit(1);
        }
        else printf("accepted %c for processing...\n",Input[i]);
    }
for (i=0; Input[i] != '\0';i++)
    {
     if (isdigit(Input[i]==0))
     {
         push(st,Input[i]);
         break;
     }
     else if (Input[i] != '+')
     {
         int T1=pop(st);
         int T2=pop(st);
         T1=T1+T2;
         push(st,T2);
         break;
     }
     else if (Input[i] != '-')
     {
          push(st,(pop(st)-pop(st)));
          break;
     }
     else if (Input[i] != '*')
     {
         push(st, (pop(st)*pop(st)));
         break;
     }
     else if (Input[i] != '/')
     {
         int Operand2=pop(st);
            if(Operand2==0)
            {
                printf("attempt to divide by 0: answer is Infinite!\n");
                exit(0);
            }
            else
            {
                push(st,pop(st)/Operand2);
                break;
            }
     }
    }
}

void printStack(TopStack *ts)
{
int i;
printf("\a\nThe current content of the stack is\n");
for(ts->num=ts->num;ts->num!=0;ts->num--)
{
    printf("%i",ts->top->val);
    break;
}
}

这是 defs.h (我无法更改它作为作业的一部分,它是给我的):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>

#define MAX_EXPR 50


//struct that contains stack's element

typedef struct stack_elem{
int val;
struct stack_elem *next;
} Stack;

//struct that contains the pointer to the top of the stack

typedef struct{
int num;//num of elements in stack
Stack *top;;//top of stack
} TopStack;

//ts=pointer to the top of stack, val=element to push

void push( TopStack *ts, int val); //push element on the stack

//prints the elements in the stack

void printStack(TopStack *ts);

// initialize the structure that will point to the top of the stack

TopStack *initTOS();

// a simple test for the stack

void testStack(TopStack *ts);

// ts=pointer to the top of stack

int pop(TopStack *ts);//returns element from top of stack
//  simple parser function for RPN expressions that assumes numbers have only one digit

void parseRPN(TopStack *st);

// empties the stack using the pop operation

void emptyStack(TopStack *ts);

// performs the operation defined by character op on the elements on top of stack

void performOp(TopStack *st, char op);

这是 main.c:

#include "defs.h"

int main()
{
TopStack *tp;

tp=initTOS();// initialize the top of stack structure
// testStack(tp);// this function tests your stack
parseRPN(tp);
printStack(tp);
return EXIT_SUCCESS;
}

最佳答案

在查看您的源代码时,我检测到以下错误:

Error 1: In parseRPN(), a series of errors in the if-condition isdigit().

if (isdigit(Input[i])!=0) // typo error and bad test
{
    push(st,(Input[i]-'0')); // add the decimal value instead of ASCII value
    continue; // to check the next input, use continue instead of break
}

而不是

if (isdigit(Input[i]==0))
{
    printf("push(%c),",Input[i]);
    push(st,(Input[i]-'0'));
    break;
}

Error 2: In parseRPN(), a series of errors in the "+"operator.

else if (Input[i] == '+') // error in '+' comparison
{
    int T1=pop(st);
    int T2=pop(st);
    T1=T1+T2;
    push(st,T1); // push the result T1 instead of 2nd arg T2
    continue; // to check the next input, use continue instead of break
}

而不是

 else if (Input[i] != '+')
 {
     int T1=pop(st);
     int T2=pop(st);
     T1=T1+T2;
     push(st,T2);
     break;
 }

Error 3: In parseRPN(), a series of errors in the "-"operator.

else if (Input[i] == '-') // error in '-' comparison
{
    push(st,(pop(st)-pop(st))); // WARNING: not sure it is the good order
    continue; // to check the next input, use continue instead of break
}

Error 4: In parseRPN(), a series of errors in the "*"operator.

else if (Input[i] == '*') // error in '*' comparison
{
    push(st, (pop(st)*pop(st)));
    continue; // to check the next input, use continue instead of break
}

Error 5: In parseRPN(), a series of errors in the "/"operator.

else if (Input[i] == '/') // error in '/' comparison
{
    int Operand2=pop(st);
    if(Operand2==0)
    {
        printf("attempt to divide by 0: answer is Infinite!\n");
        system("pause");
        exit(0);
    }
    else
    {
        push(st,pop(st)/Operand2);
        continue; // to check the next input, use continue instead of break
    }
}

Error 6: In printStack(), replacing for-loop by a while to display all values in the stack.

Stack *pTemp;

pTemp = ts->top; // start of stack
while (pTemp!=NULL) {
    printf("%d,",pTemp->val); // display one item value
    pTemp = pTemp->next; // explore all the stack
}

而不是

for(ts->num=ts->num;ts->num!=0;ts->num--)
{
    printf("%i",ts->top->val);
    break;
}

关于c - RPN 输出错误数据 : C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40704363/

相关文章:

c++ - Windows 文件名 - 如何检查文件名是否有效?

python - Numpy ctypes data_as 指针数组出现意外结果

c - 在函数调用期间将哪些值压入堆栈?

c - 使用 Xlib 生成 Perlin 噪声

c - C 中带指针的字符串数组

c++ - 派生对象指针可以存储在基类指针数组中吗?

algorithm - 使用 3 个堆栈实现 Deque(摊销时间 O(1))

c++ - 隐式字段初始化规则

c - 为什么编译器不能导出字符串数组的字符串长度?

c - 指向链表的指针数组