修改链表中的头指针 [英] Modifying head pointer in a linked list
问题描述
我无法理解此代码.我真正需要的是修改头指针以指向第一个元素.那么为什么 *head 不工作呢?更改 *head 的值会更改此指针指向的位置,这应该可以工作,对吗?我已经阅读了通过引用/通过值传递,但我发现它很难理解.有人可以帮助澄清这一点吗?感谢你的帮助.谢谢.
I am having trouble understanding this code. All I really need is to modify the head pointer to point to the first element. So why won't *head work ? Changing the value of *head changes where this pointer points to and that should work, right ? I have read the pass by reference/pass by value, but am finding it hard to understand. Can someone help clarify this ? Appreciate your help. Thanks.
在 C/C++ 中,指针误用更容易出错.考虑以下用于在列表前面插入元素的 C/C++ 代码:
In C/C++ it’s easier to make mistakes with pointer misuse. Consider this C/C++ code for inserting an element at the front of a list:
bool insertInFront( IntElement *head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
head = newElem; // Incorrect!
return true;
}
前面的代码是不正确的,因为它只更新了头指针的本地副本.正确的版本传入一个指向头指针的指针:
The preceding code is incorrect because it only updates the local copy of the head pointer. The correct version passes in a pointer to the head pointer:
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElen->data = data;
*head = newElem; // Correctly updates head
return true;
}
推荐答案
您需要帮助来理解其中的区别,对吗?
You need help understanding the difference right?
想象第一种情况下函数的调用者:
Imagine the caller of the function in the first case:
IntElement *head;
int data;
...
insertInFront (head, data);
现在,在这种情况下,head 指向的地址被放置在堆栈中并作为参数传入 insertInFront.当 insertInFront 做 head = newElement;仅修改参数(在堆栈上).
Now, in this case, the address pointed to by head is placed on the stack and passed in as an argument to insertInFront. When insertInFront does head = newElement; only the argument (on the stack) is modified.
在第二种情况下,调用者是:
In the second case, the caller would be:
IntElement *head;
int data;
...
insertInFront (&head, data);
在这种情况下,head 的地址被放置在堆栈中并作为参数传入 insertInFront.当你做 *head = newElement 时,这个传入的地址被取消引用以获得原始列表头的地址,并被修改.
In this case, the address of head is placed on the stack and passed in as an argument to insertInFront. When you do *head = newElement, this passed in address is de-referenced to get the address of the original list head, and that is modified.
这篇关于修改链表中的头指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!