2014-11-03 26 views
0

我想实现一个基本的char堆栈来增加我对堆栈的理解。林困惑,为什么我能够正确推入堆栈,但我不能弹出形成堆栈,我得到一个seg故障。从char的堆栈流行(char&)fcn

这是我的头文件

#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; 
} 
+0

您将'top'初始化为0,但您测试它是否等于-1以确定它是否为空。其中之一是不正确的。正如所写,你可以构建一个'Stack',然后立即调用'pop()'(理论上)成功。你的'push()'也不会真正把传入的值放到你的数组中。 – cdhowie 2014-11-03 23:56:20

+0

@cdhowie我修正了我的初始化,肯定是一个错字。我如何修改推送实际值,并弹出一个值? – matt 2014-11-03 23:58:47

回答

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

这些线正在创造新的本地变量在构造函数中。这意味着类中的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]) 
    { } 
    
+0

感谢您的帮助,seg故障不再存在。因此,通过说data = new char [a],我把这个局部变量移动到一个堆栈中,我可以把它弄乱? 还有,top = -1,我不需要int top = 1,因为我已经在.h中说过它的int了。 – matt 2014-11-04 00:03:34

+0

@matt通过说'data = new char [a]'你是堆 - 分配一个新的包含'a'元素的'char'数组,并在'Stack'对象的'data'字段中存储一个指向这个数组的指针。 'char * data = new char [a]'除了将指针存储在构造函数的局部变量中,它是一个变量,当构造函数返回时会丢失一个变量。 – cdhowie 2014-11-04 00:04:44

0

你应该让你的心是否要top成为顶级元素的索引,或数量元素在堆栈上,因此一个在顶部。后者更常见,并且适合初始化top = 0。但是,您希望在pop方法中检查top == 0,并且您还希望首先将top减1并在减量后使用它来索引该元素。