从主指针函数中打印出一个指针数组
问题描述:
这是来自我的.hpp文件。从主指针函数中打印出一个指针数组
struct Item{
std::string todo;};
const int MAX_STACK_SIZE = 5;
class StackArray
{
public:
StackArray();
bool isEmpty();
bool isFull();
void push(std::string Item);
void pop();
Item* peek();
int getStackTop() { return stackTop; }
Item** getStack() { return stack; }
private:
int stackTop;
Item* stack[MAX_STACK_SIZE];
};
#endif
以下是我的.cpp文件的一部分功能。
void StackArray::push(std::string Item)
{
if (isFull())
{
cout<<"Stack full, cannot add new todo item."<<endl;
}
else
{
stackTop++;
Item* newStack = new Item[MAX_STACK_SIZE];
newStack[stackTop].todo = Item;
}
}
我真的很困惑在main.cpp文件中打印堆栈数组。我怎样才能做到这一点?现在我得到了,但只能打印出地址。
int main()
{
StackArray stackArray;
if (stackArray.isEmpty())
cout<< "Empty stack." <<endl;
stackArray.push("25");
stackArray.push("20");
stackArray.push("15");
stackArray.push("10");
Item**stack1=new Item*[5];
*stack1=new Item;
stack1=stackArray.getStack();
for(int i=0;i<5;i++)
{
cout<<*(stack1+i)<<endl;
}
}
答
您的push
方法实际上从未真正向stack
添加任何内容。它分配一个全新的指针数组,但它只分配给一个局部变量,当函数结束时它会消失。它应该将该项目添加到stack
。
void TodoStackArray::push(std::string Item)
{
if (isFull())
{
cout<<"Stack full, cannot add new todo item."<<endl;
}
else
{
stackTop++;
stack[stackTop] = new Item;
stack[stackTop]->todo = Item;
}
}
要打印出项目,您需要间接通过指针。
for (int i = 0; i < 5; i++) {
cout << stack1[i]->todo << '\n';
}
你永远不会在任何地方永久保存'newStack',所以你正在泄漏内存。 – Barmar
为什么你不只是将项目添加到'stack'? – Barmar
'cout todo;'除了它可能会崩溃,因为你从来没有事实上初始化'StackArray :: stack'的内容;它包含随机垃圾。 –