c++ - 如何在堆栈上分配指向指针的指针以及如何在堆上分配指针?

标签 c++ pointers heap-memory stack-memory

这是将指针分配到堆栈和堆上的指针的正确方法吗?如果不是,那么正确的做法是什么?

int a=7;
int* mrPointer=&a;
*mrPointer;

int** iptr; // iptr is on stack
*iptr=mrPointer; //not OK
int** iptr_h = new int*(); // iptr_h is on heap
*iptr_h=mrPointer;

感谢 Mat 的回答,现在我知道这是将它放入堆栈的正确方法:

int** iptr; // iptr is on stack
iptr=&mrPointer;

堆上的这个:

int** iptr_h = new int*(); // iptr_h is on heap
*iptr_h=mrPointer;

最佳答案

如果您想要一个指向最终指向 a 变量的指针,那么您可以这样做。

int a=7;
int* mrPointer=&a;
*mrPointer;

int** iptr; // iptr is on stack
iptr=&mrPointer;

编辑:澄清一下,在上面的代码中,我将 *iptr = mrPointer; 更改为 iptr = &mrPointer;

这确实会通过堆指向同一个地方。

int** iptr_h = new int*(); // iptr_h is on heap
*iptr_h=mrPointer;

根据评论编辑解释:

还可以看到需要做这样的事情:

int* mrsPointer;
int** iptr = &mrsPointer;
*iptr = mrPointer;

关于c++ - 如何在堆栈上分配指向指针的指针以及如何在堆上分配指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451069/

相关文章:

c - 代码输出说明

c++ - 段错误 - 读取初始化指针数组

hadoop - 区域服务器死亡的原因

fortran - 当 Fortran 生成大型内部临时数组时,如何避免堆栈溢出?

c++ - 如何删除 QString 的前两个字符

c++ - 模板特化是扩展还是覆盖通用模板?

c++ - 关于数据对齐的困惑

c++ - 是否有一个跨平台的 C/C++ 库可以为我们提供 CPU 和内存使用情况统计信息?

c++ - 将 C++ 双缓冲区传递给 Node Js(直接)[Node JS : V8 c++ : Nan]

c++ - 指针和双向链表