从 Main 中的双指针函数打印出指针数组
print out an pointer array from a double pointer function in main
这是来自我的.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';
}
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址