为什么在测试堆栈时此代码会崩溃?

时间:2013-12-01 13:09:15

标签: c++ stack runtime-error push pop

好的,所以我编辑了我的代码,但我仍有两个问题:

但这是我的代码:

    #include <iostream>
using namespace std;

struct stack
{
    int data[5];
    int top;
};

void push (int a, stack &S)
{
    S.top++;

    if (S.top<5)
    {
        S.data[S.top]=a;
    }
    else cout<<"Stack is full!!!"<<endl; S.top--;
}


int pop(stack &S)
{
    if (S.top==-1)
    {
        cout<<"Stack is empty!"<<endl;
    }
    else
    {
        int temp=S.data[S.top];
        S.data[S.top]=NULL;
        S.top--;
        return temp;
    }
}

bool isEMPTY(stack &S)
{
    if (S.top==-1)
        return true;
    else return false;
}
bool isFULL(stack &S)
{
    if (S.top==5)
        return true;
    else return false;
}


int main()
{
    stack S = { {}, -1 };

    push(5,S); cout<<"5 is pushed \n"<<endl;
    push(3,S); cout<<"3 is pushed \n"<<endl;
    push(1,S); cout<<"1 is pushed \n"<<endl;
    push(2,S); cout<<"2 is pushed \n"<<endl;
    push(6,S); cout<<"6 is pushed \n"<<endl;
    push(7,S); cout<<"7 is pushed \n"<<endl;

    cout<<pop(S)<<"is popped\n"<<endl;
    cout<<pop(S)<<"is popped\n"<<endl;
    cout<<pop(S)<<"is popped\n"<<endl;

    return 0;
}

所以,第一个问题是,当我弹出时,我得到一个“完全随机的值”并且它不像LIFO。

其次,我实际上打算插入6个值,当我已经有最大值= 5时,输出实际上显示了6个值。

4 个答案:

答案 0 :(得分:2)

stack S;

由于stack是POD,因此上述行不会初始化成员top。因此,在toppush函数中使用未初始化的pop会调用未定义的行为。

写下这个:

stack S {}; //must be compiled in C++11 mode, else write : stack S = stack();

此值初始化S及其成员,即top初始化为0。其余的代码可能仍然有其他问题,但至少你已经解决了正确的初始化问题。 如果您使用0作为top的初始值,则会相应地写出pushpop的逻辑!

修复后,在推送从堆栈中弹出值之前检查top的值,因为成员数组最多可以有{{} 1}}元素,当它为空时你不能弹出更多的元素。你必须保持这些不变量。

答案 1 :(得分:1)

我没有看到创建类型堆栈对象的位置以及如何初始化数据成员top。 另外,请使用nto帐户,成员函数push不会检查是否尝试在数组之外添加项目。

您应该按以下方式定义对象

stack S = { {}, -1 };

答案 2 :(得分:1)

 else cout<<"Stack is full!!!"<<endl; S.top--;

与:

相同
else
{
cout<<"Stack is full!!!"<<endl;
} 
S.top--;

作为一般规则,尽量避免:编写if / else而不使用大括号,并避免在同一行中编写多行代码。

答案 3 :(得分:0)

错误是:

  1. stack s; //你定义了本地变量“s”而未经过初始化。
  2. push(5,s); //将uninlitialized“s”传递给函数“push”,在调试代码时,“s.top”不是预期的“-1”,但有些值不可思议〜(经常超过5),所以你的推送操作失败了!
  3. stack S;
    S.top = -1;
    for(int i = 0; i < 5; i++)
    {
        S.data[i] = 0;
    }
    

    stack S; S.top = -1; for(int i = 0; i < 5; i++) { S.data[i] = 0; }