2015-09-14 90 views
-5

这是我的程序,使用堆栈将表达式从后缀转换为中缀。我没有得到任何错误,但在运行时,编译器说Segmentation Fault - Core Dumped。我认为这与指向垃圾值的指针有关。如何tracebck到这个流氓指针?另外,有没有更好的方法将Postfix转换为中缀?分割错误 - 核心转储

#include<iostream> 
#include<string.h> 
#include<stdio.h> 
#include<math.h> 
class StringStack 
{ 
    public: 
    char arr[20][20]; 
    int top; 
    StringStack() 
    {top=-1; arr[20][20]={NULL};} 
    void push(char* a) 
    {strcpy(arr[++top],a);} 
    char* pop() 
    {return arr[top--];} 
}; 
void paranthesise(char a[]) 
{ 
    int l = strlen(a); 
    a[l+2] = '\0'; 
    for(int i=l; i>=0; i++) 
     a[i] = a[i-1]; 
    a[0] = '('; 
    a[l+1] = ')'; 

} 
using namespace std; 
int main() 
{ 
    char temp[1]; 
    char postfix[20] = ""; 
    char temp2[10] = ""; 
    char temp3[10] = ""; 
    StringStack s1; 
    cout<<"Enter Postfix Expression: "<<endl; 
    gets(postfix); int l = strlen(postfix); 
    for(int i=0; i<l; i++) 
    { 
     if(postfix[i]!='*'&&postfix[i]!='/'&&postfix[i]!='+'&&postfix[i]!='-') 
     { 
      temp[0]=postfix[i]; 
      s1.push(temp); 
     } 
     else 
     { 
      strcpy(temp2,s1.pop()); 
      strcpy(temp3,s1.pop()); 
      switch(postfix[i]) 
      { 
       case'*': 
        temp[0]='*'; break; 
       case'/': 
        temp[0]='/'; break; 
       case'+': 
        temp[0]='+'; break; 
       case'-': 
        temp[0]='-'; break; 

       default: cout<<"Error"; break; 
      } 
      strcat(temp3,temp); 
      strcat(temp3,temp2); 
      paranthesise(temp3); 
      s1.push(temp3); 
     } 
    } 
    strcpy(temp2,s1.pop()); 
    cout<<"\nInfix:"; 
    puts(temp2); 
    return 0; 
} 
+1

可能的重复项:[#1](http://stackoverflow.com/q/20612172),[#2](http://stackoverflow.com/q/22546079),[#3](http:/ /stackoverflow.com/q/4363133)。 –

+0

在'paranthesise'中:'for(int i = l; i> = 0; i ++)'我猜你在这里想要'我 - '。 – user657267

+1

*“另外,有没有更好的方法将Postfix转换为中缀?”*太宽泛。 –

回答

2

的问题,我发现:

一个

arr[20][20]={NULL}; 

是错误的。这将NULL分配给arr[20][20],这不是数组的有效元素。你正在设置你不应该记忆的值。 arr的有效元素是arr[0][0] - arr[19][19]

这本身就足以让程序展现未定义的行为。当您使用

char temp[1]; 

它所能容纳的唯一有效的字符串是空字符串

StringStack() : arr{}, top(-1) {} 

两个

我会构造改变。既然你打算用它持有一个字符串由一个字符,你需要使用:

char temp[2] = ""; // Doesn't have to be 2 but it has to be 
        // greater than 1. 

paranthesise,您有:

for(int i=l; i>=0; i++) 

需要被:

for(int i=l; i>=0; i--) 

否则,您不断修改数组而不满足标准来结束循环。不仅如此,您还最终修改了超出有效限制的数组。