为什么弹出我的堆栈会返回垃圾而不是初始变量?
Why does popping off my stack return garbage instead of the initial variables?
当我运行我的程序时,它完美地将数字推入数组。但是当它弹出它们,然后打印它们时,我得到了垃圾数字。问题是否与我的主要功能有关? 还是我没有在 Stack 类中正确初始化我的数组?起初我的构造函数遇到了一些问题,但在进行一些调整后它似乎工作正常。
有什么突出的关于为什么我在运行脚本后收到垃圾号码
?#include<iostream>
#include<cstdlib>
#ifndef MYSTACK_H
#define MYSTACK_H
#include<iostream>
#include<new>
using namespace std;
class MyStack
{
private:
int *list;
int top;
int max;
public:
MyStack(int m)
{
int max = m;
list = new int[max];
int top = -1;
}
~MyStack()
{
delete[] list;
}
int push(int);
int pop();
int peek(int &a) const;
};
int MyStack::push(int a)
{
if (top < max - 1)
{
top = top + 1;
list[top] = a;
return 0;
}
return -1;
}
int MyStack::pop()
{
if (top > -1)
{
top = top - 1;
return 0;
}
return -1;
}
int MyStack::peek(int &a) const
{
if (top > -1)
{
return(list[top]);
return 0;
}
return -1;
}
#endif
int main()
{
MyStack m(5);
for (int i = 0; i < 6; i++)
{
int x = 1 + rand() % 100;
cout << x << "t";
m.push(x);
}
cout << "n";
for (int i = 0; i < 6; i++)
{
int x;
m.peek(x);
cout << x << "t";
m.pop();
}
cout << "n";
system("pause>nul");
}
调用MyStack
构造函数后未设置top
和max
,您正在创建局部变量,成员不受影响:
int max = m; // local
list = new int[max];
int top = -1; // local
更改为
max = m;
list = new int[max];
top = -1;
>参数a
永远不会在peek()
函数中使用:
int MyStack::peek(int &a) const
{
if (top > -1)
{
return(list[top]); // you return the value instead of assigning it to "a"
return 0; // unreachable by the way
}
return -1;
}
相关文章:
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 为什么我的变量存在于其范围之外
- 为什么我的字符串变量没有打印完整的字符串?
- 为什么我的 c++ 程序检查不是初始化的变量?
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- 为什么弹出我的堆栈会返回垃圾而不是初始变量?
- 我的包装函数缺少变量?
- 在我的变量打印C++后无法获得 $ 打印符号
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 为什么我的双变量通过添加 c++ 显示 nan?
- 我应该使我的局部变量常量还是可移动的
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 我可以在我的类中使用 omnetpp.ini 变量吗?
- 我的类中应该有一个Allocator作为成员变量吗
- 我可以在初始化之前使用 std::array 成员变量中的 data() 指针吗?发出警告
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么我的程序没有更改结构变量中的值?