从char的堆栈中弹出(char&)fcn

时间:2014-11-03 23:51:26

标签: c++ stack

我正在尝试实现一个基本的char堆栈,以增加我对堆栈的理解。我很困惑为什么我能够正确地推入堆栈,但我无法从堆栈中弹出,我得到一个段错误。

这是我的头文件

#include <iostream>

using namespace std;

class Stack {
    public:
            Stack(int = 10);
            Stack(const Stack&);
            ~Stack();
            Stack& operator=(const Stack&);
            bool push(char);
            bool pop(char &);
            bool empty() const;
            bool full() const;
            bool clear();
    bool operator==(const Stack&) const;
            //friend ostream& operator<<(ostream&, const Stack&);
    private:
            int max;
            int top;
            int actual; //only used in stack (stay) implementation
            char* data;
};

这是我的实施文件,仅包含相关信息

#include <iostream>
#include "stack.h"

using namespace std;

const int MAX = 9;

Stack::Stack(int a) {
    max = a;
    char *data = new char[a];
    int top = 0;
}

Stack::~Stack()
{
    delete[] data;
    data = NULL;
}


bool Stack::push(char c)
{
    if(top==9)
    {
        cout << "stack is full" <<endl;
        return false;
    }
    else
    top++;
    return c;
}

bool Stack::pop(char &c) 
{
    if(top==-1)
    {
        cout << "Stack is empty" << endl;
        return false;
    }
    c = data[top];
    top--;
    return c;

}

这是我的测试文件

    #include <iostream>
    #include "stack.h"
    //#include "queue.h"

using namespace std;

int main()
{
    Stack *stack = new Stack(10);

    char s = 's';
    char t = 't';
    char a = 'a';
    char c = 'c';
    char k = 'k';

    stack->push(s);
    stack->push(t);
    stack->push(a);
    stack->push(c);
    stack->push(k);
    // this is where it seg faults
    stack->pop(s);
    stack->pop(t);
    stack->pop(a);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

char *data = new char[a];
int top = 0;

这些行在构造函数中创建新的 local 变量。这意味着类中的data字段永远不会被分配,因此是未初始化的指针;您正试图从pop()中的未定义内存位置读取值。

您需要设置对象的数据成员:

data = new char[a];
top = -1; // Should actually be -1 according to your test in pop()

其他一些说明:

  • push()中,您实际上从未将参数存储在data中,因此永远不会将其读回。 pop()将从未初始化的内存中返回数据,因此您尝试弹出的char将是垃圾。
  • 在构造函数中,您可以使用初始化列表而不是赋值:

    Stack::Stack(int a)
        : max(a),
          top(-1),
          data(new char[a])
    { }
    

答案 1 :(得分:0)

您应该决定是否希望top成为顶部元素的索引,或者是堆栈上元素的数量,因此是一个超过顶部的元素。后者更常见,适合初始化top = 0。但是,您希望在top == 0方法中检查pop,并且还希望首先递减top并使用它在元素递减后对其进行索引。