【问题标题】:C: Stack Dump error for infix to postfix conversionC:中缀到后缀转换的堆栈转储错误
【发布时间】:2015-02-14 12:13:56
【问题描述】:

我编写了以下代码将中缀表达式转换为后缀,但显示运行时错误。

错误如下:

输入字符串:a+b-c*d 1 [main] infix_to_postfix 7340 cygwin_exception::open_stackdumpfile:将堆栈跟踪转储到 infix_to_postfix.exe.stackdump

以下是我的代码:

#include<stdio.h>
#include<string.h>
#define size 20

struct stack{
    int a[size],top;
    int temp[size], tos;
}s;

// Push operation....
void push(struct stack s,int item){
    if(s.top >= size-1){
        printf("\nStack overflow..\n");
    }
    else{
        s.a[++s.top] = item;
    }
}

// Pop operation....
int pop(struct stack s){
    if(s.top == -1){
        printf("\n..Stack underflow..\n");
}
else {
    return s.a[s.top--];
}
}


// function f starts from here. f returns the precedence value of corresponding symbol.
int f(char symbol){
    if (symbol == '+' || '-')
        return 1;
    if (symbol == '*' || '/')
        return 2;
    if (symbol == '#')
        return 0;
    char c;
for(c='a'; c<='z'; c++){
    if(symbol == c)
        return 3;
}
}

int main(){
s.top = -1;
s.a[++s.top] = '#';

int i = 0;
char input[20], polish[21];
char next, temp;

printf("Input string: ");
scanf("%s", input);
strcat(input, '#');
next = input[i++];

while(next != '\0'){
    while(f(next) > f(s.a[s.top])){
        push(s, next);
        next = input[i++];
    }
    while(f(next) <= f(s.a[s.top])){
        temp = pop(s);
        strcat(polish, temp);
        printf("\nPolish: %s", polish);
    }
}


return 0;
}

【问题讨论】:

  • 注意:function(struct stack s, ... 按值调用。
  • 并且strcat 的参数是char *,而不是char

标签: c data-conversion infix-notation stack-dump


【解决方案1】:
strcat(polish, temp);

polish 从未初始化,因此使用未初始化的数组会导致未定义的行为。strcat() 需要一个以 null 结尾的字符串。

尝试做类似的事情

char polish[21] = "";

编辑:

正如 @BLUEPIXY 指出的那样,strcat() 期望 char * 而不是 char

【讨论】:

    猜你喜欢
    • 2013-03-28
    • 2015-09-13
    • 2013-07-12
    • 2015-09-12
    • 1970-01-01
    • 2012-04-03
    • 2013-11-08
    • 2012-09-22
    • 2015-04-19
    相关资源
    最近更新 更多