从 Main 中的双指针函数打印出指针数组

print out an pointer array from a double pointer function in main

本文关键字:指针 函数 打印 数组 Main      更新时间:2023-10-16

这是来自我的.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';
}