【问题标题】:SPOJ - Runtime error SIGSEGVSPOJ - 运行时错误 SIGSEGV
【发布时间】:2017-03-22 03:41:35
【问题描述】:

以下是 infix 到 postfix 转换的实现,它在我的计算机上运行良好,但是当我在 SPOJ 上提交时,它给了我 运行时错误 SIGSEGV ,我是竞技编程新手,无法处理此类错误。

#include <iostream>
#include <stack>
#include<string.h>
#include<ctype.h>
using namespace std;
int prec(char ch){
    switch(ch){
        case '^' : return 3;
                    break;
        case '*':
        case '/': return 2;
                break;
        case '+':
        case '-': return 1;
                break;
        default: return -1;
    }
}
void pti(char a[]){
    stack<int> post;
    int k = -1;
    for(int i = 0;i<strlen(a);i++){
        if(isalnum(a[i]))
            a[++k] = a[i];
        else if(a[i] == '(')
            post.push(a[i]);
        else if(a[i] == ')'){
            while(!post.empty() && post.top()!= '('){
                a[++k] = post.top();
                post.pop();
            }
            post.pop();
        }
        else {
            while(!post.empty() && prec(a[i]) <= prec(post.top())){
                a[++k] = post.top();
                post.pop();
            }
            post.push(a[i]);
        }
    }
    while(!post.empty()){
        a[++k] = post.top();
        post.pop();
    }
    a[++k] = '\0';
    cout<<a<<endl;
}
int main()
{
   int t;
   cin>>t;
   for(int i = 0;i<t;i++){
        char a[100];
        cin>>a;
        pti(a);
   }
}

【问题讨论】:

  • 如果用户输入大于 100 会发生什么?另外,更喜欢 std::string 而不是 char 数组

标签: c++11 stack runtime-error segmentation-fault


【解决方案1】:

您只需要使输入数组更长,例如1000 的大小得到 AC。

SIGSEGV 信号表示发生了分段错误,这基本上意味着您访问了不属于您的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多