【发布时间】:2014-09-18 12:32:59
【问题描述】:
这段代码在我的机器上运行良好,但是当我将它上传到 codechef 时,它给了我一个运行时错误 SIGSEGV。谁能指出我的代码中的错误?这是我为http://www.codechef.com/problems/ONP/提出的问题
#include<iostream>
#include<string>
using namespace std;
class stack
{
public:
void push(char a)
{
++top;
arr[top]=a;
}
void pop()
{
top--;
}
void initialize(int size)
{
top=-1;
max=size;
}
bool chckfull()
{
return (top==max-1);
}
bool chckempty()
{
return (top==-1);
}
char front()
{
return arr[top];
}
private:
int top;
int max;
char arr[404];
};
int chckalphanum(char y)
{
if((y>='a')&&(y<='z'))
return 1;
else if ((y>='A')&&(y<'Z'))
return 1;
else if((y>='0')&&(y<='9'))
return 1;
return 0;
}
int pre(char x)
{
if(chckalphanum(x))
return 0;
if(x=='(')
return -1;
else if(x=='^')
return 3;
else if((x=='/')||(x=='*'))
return 2;
else
return 1;
}
int main ()
{
std::ios::sync_with_stdio(false);
string s, s1=")";
char q[404];
int qmax=0,t;
stack prs;
scanf("%d", &t);
while(t--)
{
cin>>s;
prs.initialize(s.length());
prs.push('(');
s=s+s1;
for(int i=0; i<s.length(); i++)
{
if(s[i]=='(')
prs.push('(');
else if(chckalphanum(s[i]))
{
q[qmax]=s[i];
qmax++;
}
else if(s[i]==')')
{
while(prs.front()!='(')
{
q[qmax]=prs.front();
qmax++;
prs.pop();
}
prs.pop();
}
else
{
while(pre(prs.front())>=pre(s[i]))
{
q[qmax]=prs.front();
qmax++;
prs.pop();
}
prs.push(s[i]);
}
}
for(int i=0; i<qmax; i++)
cout<<q[i];
cout<<"\n";
qmax=0;
}
return 0;
}
【问题讨论】:
-
我愿意。我写了一个初始化函数。并将顶部初始化为 -1。
-
我也调用了那个函数。就在我输入字符串之后。
-
是的,我现在明白了!让我检查错误。!非常感谢您抽出宝贵的时间 :) 它的代码很大
-
除非你以某种方式达到极限(说真的,你的堆栈应该做一些边界检查,你也可以使用
at()将数组替换为向量来检查),我看不到任何立即错误。 -
@PranjalRanjan 边界检查是不必要的,前提是您可以确定您永远不会创建包含错误的代码。你至少应该确保你不会推入一个完整的堆栈或弹出一个空的堆栈。
标签: c++ runtime iostream segmentation-fault