无法弄清楚指针行为

Unable to figure out pointers behaviour

本文关键字:指针 弄清楚      更新时间:2023-10-16

我无法弄清楚为什么temp->next=NULL打破原始链接列表

我的代码在这里:

struct Node{
    int data;
    Node* next;
};
Node* createNode(int data)
{
    Node* temp=new Node;
    temp->data=data;
    temp->next=NULL;
    return temp;
}
int main()
{
Node* root=createNode(1);
root->next=createNode(2);
root->next->next=createNode(3);
display(root);
cout<<"nAddress of root = "<<&root<<"-> "<<&(root->next)<<"-> "<<&(root->next->next);
Node* temp=root;
temp->next=NULL;  //Trying to set next pointer to Null in temp list but instead it is impacting the original list by nullifying the next node. Why is it so ?
display(temp);
cout<<"nAddress of temp = "<<&temp<<"-> "<<&(temp->next);
display(root);  // Original list broke
}

输出:

Linked list => 1->2->3
Address of root = 0x7ffd3afbc2f0-> 0x5605aff6cc28-> 0x5605aff6cc48
Linked list => 1
Address of temp = 0x7ffd3afbc2f8-> 0x5605aff6cc28
Linked list => 1

考虑指针int* ptr;和整数int var;。以同样的方式, &var是整数的地址,与其值不同, &ptr是指针的地址,与其值不同( what what ,它指向(。

表达式Node* temp=root;正在创建一个指针temp,其值与root相同,它们是指同一对象。temproot是不同的对象,并且具有不同的地址(&root&temp不同(,但是它们具有相同的值(roottemp相等(。因此,temp->nextroot->next是相同的指针。更改一个会改变另一个。

在您的示例中,只有一个链接列表, roottemp都参考。

指针只是指向内存中的一个位置,因此他们的名字。当您这样做时:

Node* temp=root;

您创建一个指向与指针root相同内存位置的指针temp。因此:

temp->next=NULL;

和此:

root->next=NULL;

做完全相同的事情,因为temp->nextroot->next是相同的。