-3 c++ while-loop
这是我的第一个数据结构程序.我正在使用带有push,pop和initialize函数的数组实现一个简单的堆栈.我得到一个无限循环作为输出.你能告诉我为什么会这样吗?
#include<iostream>
using namespace std;
# define SIZE 6
class stack{
public:
void init();
void push(int i);
int pop();
int top;
int stck[SIZE];//bydefault private
};
void stack::init()
{
top=0;
return;
}
void stack::push(int i)
{
if(top==SIZE)
{
cout<<"stack is full";
return;
}
else
{
top=top+1;
stck[top]= i;
return;
}
}
int stack::pop()
{
if(top==0)
{
cout<<"stack is empty. \n";
return 0;
}
else
{
top = top-1;
return(stck[top-1]);
}
}
int main()
{
stack stack1;
stack1.init();
int a;
int m;
while(a!=4)
{
cout<<"1. push 2. pop 3.display 4.exit .\n";
cin>>a;
if(a==1){
cout<< "enter value";
cin>>m;
stack1.push(m);
}
if(a==2)
{
cout<<"popped"<< stack1.pop();
}
if(a==3)
{
for(int k=0; k<=stack1.top;k++)
{
cout<<stack1.stck[k];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您永远不会初始化a,因此您的程序具有未定义的行为.具体来说,该while (a != 4)行执行左值到右值的转换,a而其值是不确定的,C++标准在4.1节中明确指出为未定义的行为.
但是,我怀疑这是导致手头的问题.实际上,除非优化器只是优化了所有代码,否则程序通常应该按预期运行; 只有a == 4在第一个循环中你才遇到问题.这不会使代码可以接受,但可能还有更多.
我怀疑问题是你top用来代表一个元素数量.当你有零元素时,你指向第一个元素; 当你有一个,你指向第二个,等等.这意味着你指向第一个未使用的元素.
但是,在您push和pop函数中,您top先进行更改,然后才能访问堆栈,但就好像您没有更改它一样:
top = top + 1;
stck[top] = i;
Run Code Online (Sandbox Code Playgroud)
当您的堆栈为空时,这将设置top为1然后访问stck[1].与此同时,stck[0]未设置.弹出时,你却反其道而行之:
top = top - 1;
return stck[top-1];
Run Code Online (Sandbox Code Playgroud)
这将设置top为0,但返回stck[-1],这是超出范围.
我怀疑如果你把SIZE值推到堆栈上,你最终会覆盖不相关的内存,这可能会导致各种麻烦.我仍然没有看到无限循环将如何跟随,但鉴于行为未定义,它肯定是一个可能的结果.
(另一种方法是你在某个时候输入一个不是数字的东西.看你从未检查你的输入是否成功,如果a != 4你输入一些无效的东西,所有进一步的读取将失败,并且a将保持不等于4.你可以修复这个通过改变你while的方式
while (a != 4 && std::cin)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果输入的内容无效并std::cin进入非良好状态,则循环(以及程序)将结束.)