![](/img/trans.png)
[英]Why my head pointer is changing in linked list,even not passing it by reference?
[英]when passing head of linked list to function.Why do we need to pass it by reference of reference such as in push(node* &head, int key)
打印出head和&head的地址: head:0x603050 &head :0x7ffffffffe4b8: 什么意思?
void push(node* &head,int key)// Inserts items at front of link list
{
node* linkNode=new node(); //declares new node
linkNode->data=key;
if(head==NULL) //if the link list is empty then create a new one.
{
linkNode->next=NULL;
head=linkNode; //1
}
else
{
linkNode->next=head;
head=linkNode;
}
}
從鏈接列表調用所有其他函數的主函數是 8,4,2 主函數
int main(int argc, char** argv)
{
node* head=NULL; //initializing head to NULL
push(head,2); //creating link list
push(head,4); //this requires &head
push(head,8); //link list is 8,4,2
selectSort(head); //this does not require &head
reverse(head); //this requires &head
return 0;
}
為什么我們需要通過引用來傳遞它,比如在 push(node* &head, int key)
否則將無法將給定的linkNode
設置為當前head
:
if(head==NULL) //if the link list is empty then create a new one.
{
linkNode->next=NULL;
head=linkNode; // <- This statement changes the head variable passed from main()
}
您擁有的是對將從push()
函數“返回”的指針 ( head
) 的引用,並正確設置從調用者傳遞的head
指針:
node* head=NULL;
push(head,2); // sets head to the node created for key '2'
不要忘記delete
您使用new node();
創建的所有node
實例new node();
. 在您所展示的不同上下文中,這可能會導致內存泄漏。
那不是“參考參考”; 它是對指針的引用。
這意味着,一旦將指針head
設置為指向新元素,在函數內,此更改也會影響您最初傳遞給函數的指針。
selectSort(head); //this does not require &head
實際上,如果函數對列表的所有元素執行排序,它可能應該這樣做。
reverse(head); //this requires &head
在這個調用之后, head
現在指向列表的新頭部。 如果您想通過這將是不可能的head
按值。
另一種實現可能會return
新的頭指針,而不是使用這種“輸出參數”約定。
您必須將head
傳遞給push
函數的原因是因為您的push
函數期望修改head
指針的值。 如果您不通過引用傳遞它,對它的任何更改都將僅在函數調用中可用。 例如,如果它不是通過引用傳遞,並且您將head
(初始化為NULL
)傳遞給push
函數,則會創建一個新項目,但您的head
值只會在函數內部更新。 一旦你離開函數,它仍然是NULL
(因為你通過復制傳遞了指針)。
請注意,如果您創建一個鏈表類而不是將您的節點視為鏈表本身(即,將節點封裝在列表接口下 - 這是標准庫所做的),則這可能會消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.