以下代码来自Programming Interviews Exposed一书 我在理解指针的概念时遇到问题。为什么我们不能使用代码 no。 1.
代码1
bool insertInFront( IntElement *head, int data )
{
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
head = newElem; // Incorrect!
return true;
}
代码2
bool insertInFront( IntElement **head, int data )
{
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElen->data = data;
*head = newElem; // Correctly updates head
return true;
}
最佳答案
在代码 1 中,您将
newElem
的指针位置分配给head
的本地拷贝。当函数返回时,head
被销毁,你会发生内存泄漏(你丢失了指向newElem
的指针,让你无法delete
它。)您只更改了指针的函数的本地拷贝,调用者的拷贝不受影响。在代码 2 中,
head
是一个指向指针的指针。您不仅有一个指针,您实际上还有一个指针指向调用者的指针。这允许您更改调用者的指针,将指针存储到newElem
当函数返回时,head
被销毁,但它只是指向 a- 的指针指针。原始指针在调用者的范围内是完整的。
关于c++ - 理解指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582245/