"top"值不会改变我推送或弹出堆栈的次数
"top" value won't change how many times ever i push or pop a stack
我正在使用动态数组实现堆栈。我的想法很简单:我希望用户输入他/她想要的长度,然后创建一个具有该长度的堆栈。然后他/她可以推,弹出一个整数;查看最大值和最大值(用于调试目的(;检查它是满的还是空的(也用于调试(。他/她可以推到堆栈满然后必须弹出,他/她可以弹出直到它空然后必须推。我使用 do while 和切换以使其更容易调试和操作。 但是当我开始测试时,我的 Stack 类的顶级属性仍然是 0,我推了多少次或弹出了多少次。我一直在尝试查找错误,但仍然没有找到。
这是我的代码:
#include <cstdio>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Stack {
int top;
int max; // max index
int *data;
public:
Stack(int length);
int isEmpty();
int isFull();
int push(int n);
int pop();
int getTop(void);
int getMax(void);
~Stack(void);
};
Stack::Stack(int length){
top = 0;
max = length;
data = new int[length+1];
}
int Stack::isEmpty(void){
return top==0;
}
int Stack::isFull(void){
return top==max;
}
int Stack::push(int n){
if(!isFull()){
data[++top] = n;
return 1;
}
else return 0;
}
int Stack::pop(void){
if(!isEmpty()){
return data[top--];
}
else return -911; //rare and indicative number
}
int Stack::getTop(void){
return top;
}
int Stack::getMax(void){
return max;
}
Stack::~Stack(void){
delete[] data;
}
int main(void){
int length = 0;
cout << "Enter stack's length': "; cin >> length;
Stack list(length);
char lock;
do{
cout << "1. push" << endl;
cout << "2. pop" << endl;
cout << "3. show top index" << endl;
cout << "4. show max index" << endl;
cout << "5. isFull?" << endl;
cout << "6. isEmpty?" << endl;
cout << "0. Quit" << endl;
scanf("%d", &lock);
switch(lock){
case 1:
int temp;
cout << "Enter an integer: ";
cin >> temp;
printf(list.push(temp)?"successn":"failn");
break;
case 2:
cout << "Top's data: " << list.pop() << endl;
break;
case 3:
cout << list.getTop() << endl;
break;
case 4:
cout << list.getMax() << endl;
break;
case 5:
printf(list.isFull()?"Truen":"Falsen");
break;
case 6:
printf(list.isEmpty()?"Truen":"Falsen");
break;
case 0: break;
default:
cout << "Not an available work!" << endl;
}
} while (lock!= 0);
return 0;
}
你有微妙的内存损坏。原因:
q58036810.cpp:71:21: warning: format specifies type 'int *' but the argument has type 'char *' [-Wformat]
scanf("%d", &lock);
~~ ^~~~~
%s
当您在菜单上输入数字时,它太大而无法lock
因此覆盖了top
存储在list
中的内存。将char lock
更改为int lock
,问题应该会消失。将来,请始终使用警告进行编译并注意它们。此外,由于这个问题的性质,它不会始终如一地重现(即,它似乎在我的机器上工作正常。
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么调用堆栈数组会导致内存泄漏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈和队列是否像C++中的数组一样传递?
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 从堆栈分配的原始指针构造智能指针
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 在我自己的堆栈中实现top的问题
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- "top"值不会改变我推送或弹出堆栈的次数
- C++和 Java 数据结构的重叠:堆栈"top"与"peek"
- C++堆栈实现 - 两个版本的 top 方法
- stl 堆栈和 top() 函数的问题
- Stack.top() 在访问包含元素的堆栈时提供bad_access_code