C++ 如何阻止溢出?
在受到实验室指导老师的启发后,我做了这个小动作。我的程序可以很好地播放流行音乐,但在最后一次推送时失败了。该值在超过数组阈值后消失。有没有办法阻止这一切 如有意见,将不胜感激。谢谢:) 另外,我现在也在为自己做假面,因为我不得不使用3个全局变量。正确方向上的某个点会有所帮助C++ 如何阻止溢出?,c++,stack,global-variables,dev-c++,C++,Stack,Global Variables,Dev C++,在受到实验室指导老师的启发后,我做了这个小动作。我的程序可以很好地播放流行音乐,但在最后一次推送时失败了。该值在超过数组阈值后消失。有没有办法阻止这一切 如有意见,将不胜感激。谢谢:) 另外,我现在也在为自己做假面,因为我不得不使用3个全局变量。正确方向上的某个点会有所帮助 #include<iostream> #include<cstdlib> #include<conio.h> using namespace std; int n, *stack, *sl
#include<iostream>
#include<cstdlib>
#include<conio.h>
using namespace std;
int n, *stack, *slack;
class stacks
{
int position;
public:
stacks()
{
stack = new int[n];
slack = new int[n];
for(int i=0;i<n;i++)
stack[i]='\0';
position = 0;
}
void insert()
{
push();
position--;
system("cls");
cout<<"Enter the number to be added: ";
cin>>stack[0];
position++;
}
void push()
{
system("cls");
cout<<"The stack has been pushed";
slack[0]=0;
for(int j=0; j<n-1;j++)
{
slack[j+1]=stack[j];
}
for(int j=0; j<n;j++)
{
stack[j] = slack[j];
}
position++;
stack[0] = 0;
}
void pop()
{ system("cls");
int i=0;
if(position<1)
{
cout<<"Underflow!";
return;
}
cout<<"The number has been successfully popped from the stack!";
while(stack[i] != '\0')
{
stack[i]=slack[i];
i++;
}
for(int j = 0 ; j<i ; j++)
{
stack[j]=stack[j+1];
}
stack[i] = '\0';
position--;
}
void memusage()
{
system("cls");
cout<<"The total memory usage is: "<<position+1<<"/"<<n<<" .";
}
void display()
{
for(int j = 0 ; j<n ; j++)
{
cout<<j+1<<" Member is: "<<stack[j]<<endl;
}
}
};
int main()
{
cout<<"Enter the number of elements: ";
cin>>n;
stacks a;
char ac = 'y', b;
while( ac == 'y' || ac =='Y' || ac =='\n')
{
system("cls");
a.display();
cout<<"\n\n\n";
cout<<"Enter a new value [1]"<<endl;
cout<<"Push the stack [2]"<<endl;
cout<<"Pop the stack [3]"<<endl;
cout<<"See memory usage [4]"<<endl;
cout<<"\n\nEnter your choice[1,2,3,4]: ";
b=getch();
if(b=='1')
{a.insert();}
else if(b=='2')
{a.push();}
else if(b=='3')
{a.pop();}
else if(b=='4')
{a.memusage();}
else cout<<"\nInvalid Entry. Please choose a valid entry!\n";
cout<<"\n\nAnother?[y/Y]";
ac=getch();
}
}
#包括
#包括
#包括
使用名称空间std;
整数n,*堆栈,*松弛;
类堆栈
{
内部位置;
公众:
堆栈()
{
堆栈=新整数[n];
松弛=新整数[n];
对于(int i=0;我会遇到堆栈溢出!听起来你可能需要学习如何使用调试器来逐步完成代码。有了一个好的调试器,你可以逐行执行你的程序,看看它偏离了你的预期。如果你要做任何编程,这是一个必不可少的工具。进一步阅读:嘿,我的程序编译了w没有任何问题。只是我不知道如何阻止数组中较低的值“泄漏”。正确方向上的一点会有帮助。此外,如果有人能帮助我实现一个不使用全局函数的程序,我会很高兴。谢谢您的讲解:)调试器不会帮助您修复编译器错误;它们会帮助您逐行检查代码,以便您能够找出代码没有达到预期效果的原因。此外,我建议使用原始指针,而不是原始指针。尝试更简单的方法-不要移动堆栈元素,移动堆栈尾部指针。例如:堆栈的容量为100 and堆栈指针top
,值为0
。将元素推到堆栈上时,只需将其分配给stack[top]
并递增top
。弹出时-递减top
并返回stack[top]
。指针为零时-堆栈上没有元素,如果大于堆栈大小-使用更大的大小重新分配堆栈。