4pi*_*ie0 2 c++ heap stack pointers
这是在堆栈和堆上分配指针指针的正确方法吗?如果没有,那么这样做的正确方法是什么?
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;
Run Code Online (Sandbox Code Playgroud)
感谢Mat的回答,我知道这是将它放在堆栈上的正确方法:
int** iptr; // iptr is on stack
iptr=&mrPointer;
Run Code Online (Sandbox Code Playgroud)
这在堆上:
int** iptr_h = new int*(); // iptr_h is on heap
*iptr_h=mrPointer;
Run Code Online (Sandbox Code Playgroud)
如果你想要一个指向最终指向a
变量的指针,那么你就是这样做的.
int a=7;
int* mrPointer=&a;
*mrPointer;
int** iptr; // iptr is on stack
iptr=&mrPointer;
Run Code Online (Sandbox Code Playgroud)
编辑:澄清,在上面的代码我改*iptr = mrPointer;
到iptr = &mrPointer;
.
这确实会通过堆来指向同一个地方.
int** iptr_h = new int*(); // iptr_h is on heap
*iptr_h=mrPointer;
Run Code Online (Sandbox Code Playgroud)
根据评论编辑解释:
人们还可以看到需要做这样的事情:
int* mrsPointer;
int** iptr = &mrsPointer;
*iptr = mrPointer;
Run Code Online (Sandbox Code Playgroud)