2017-10-13 90 views
0

這是來自我的.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; 
    } 
} 
+0

你永遠不會在任何地方永久保存'newStack',所以你正在泄漏內存。 – Barmar

+0

爲什麼你不只是將項目添加到'stack'? – Barmar

+0

'cout < todo;'除了它可能會崩潰,因爲你從來沒有事實上初始化'StackArray :: stack'的內容;它包含隨機垃圾。 –

回答

1

您的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'; 
}