[C ++ STL堆栈弹出操作,尽管我检查了空堆栈,却给出了段错误

问题描述 投票:0回答:1

我在S [position]堆栈上执行了pop操作,这给出了段错误,但是top操作给出了没有错误的结果,并且在pop操作之前也执行了空检查。

无法找出导致问题的原因。

#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;

int main(){
    int bar,position;
    cout<<"Enter the number of bars: ";cin>>bar;
    cout<<"Enter the position of the bar where you want to place: ";cin>>position;
    position = position - 1;
    stack<int> S[bar];
    for(int i = bar; i>0; i--){
        S[0].push(i);
    }

    S[0].pop();

    for(int i = 1; i<bar; i++){
        if(i == position){
            S[i].push(1);
            continue;
        }
        S[i].push(S[0].top());
        S[0].pop();
    }

    for(int i = 1; i< bar; i++){
        if(S[i].top() == 2){
            if(!S[position].empty()){
                S[position].pop(); //This line generating segment fault
            }
            cout<<S[position].top();
        }
    }

}

输出:

Enter the number of bars: 3
Enter the position of the bar where you want to place: 2
Segmentation fault (core dumped)
c++ stack g++
1个回答
0
投票

如果激活警告和严格的标准,您会注意到编译器拒绝该代码。只需添加-Wall -pedantic-errors,编译器就会告诉您您使用了自动存储运行时大小的数组。

您没有堆栈,但是有整个堆栈数组。

// an array or `bar` amount of distinct stacks.
std::stack<int> S[bar];

您应该改为此:

std::stack<int> S;

你去!您现在只有一个堆栈。

之后,您需要将其余代码更改为不使用索引:S.push(...)而不是S[0].push(...)

© www.soinside.com 2019 - 2024. All rights reserved.