这是将指针分配到堆栈和堆上的指针的正确方法吗?如果不是,那么正确的做法是什么?
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/