C++ 分段故障-核心转储
这是我使用堆栈将表达式从后缀转换为中缀的程序。我没有得到任何错误,但在运行时,编译器说分段错误-核心转储。我认为这与指向垃圾值的指针有关。我如何追踪这个流氓指针?还有,有没有更好的方法将后缀转换为中缀C++ 分段故障-核心转储,c++,C++,这是我使用堆栈将表达式从后缀转换为中缀的程序。我没有得到任何错误,但在运行时,编译器说分段错误-核心转储。我认为这与指向垃圾值的指针有关。我如何追踪这个流氓指针?还有,有没有更好的方法将后缀转换为中缀 #include<iostream> #include<string.h> #include<stdio.h> #include<math.h> class StringStack { public: char arr[20][20]
#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;
}
我发现的问题:
一个
这是错误的。这将为arr[20][20]分配NULL,它不是数组的有效元素。您正在设置不应该设置的内存值。arr的有效元素为arr[0][0]-arr[19][19]
这本身就足以让程序表现出未定义的行为
我会将构造函数更改为:
StringStack() : arr{}, top(-1) {}
两个
当你使用
char temp[1];
它可以保存的唯一有效字符串是空字符串。由于要使用它来保存由一个字符组成的字符串,因此需要使用:
char temp[2] = ""; // Doesn't have to be 2 but it has to be
// greater than 1.
三
在妄想症中,你有:
for(int i=l; i>=0; i++)
这需要:
for(int i=l; i>=0; i--)
否则,您将继续修改数组,而不会满足结束循环的条件。不仅如此,您最终还修改了超出有效限制的数组。可能的重复项:,。在paranthesise中:对于int i=l;i>=0;我猜你想要我-在这里。还有,有没有更好的方法把后缀转换成中缀?太宽了。在运行时,编译器说-不,它没有。编译器是C++的一部分,它在运行之前发生。运行时,操作系统负责,C++运行库支持。SegFault是一条操作系统消息,通常由代码中的错误引起。
for(int i=l; i>=0; i--)