Dwayne Smith
Dwayne Smith

Reputation: 77

Unable to figure out pointers behaviour

I'm unable to figure out why temp->next=NULL is breaking the original linked list

My code here :

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
}

Output:

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

Upvotes: 0

Views: 55

Answers (2)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29013

Consider a pointer int* ptr; and an integer int var;. In the same way &var is the address of the integer and is distinct from it's value, &ptr is the address of the pointer and is distinct from it's value (what it points to).

The expression Node* temp=root; is creating a pointer temp with the same value as root, they refer to the same object. temp and root are different objects and have different address (&root and &temp are different), but they have the same value (root and temp are equal). As such temp->next and root->next are the same pointer. Changing one will change the other.

In your example, there only ever exists one linked list, to which root and temp both refer.

Upvotes: 3

Max Vollmer
Max Vollmer

Reputation: 8598

Pointers just point at a location in memory, hence their name. When you do this:

Node* temp=root;

you create a pointer temp pointing at the same memory location as the pointer root. So this:

temp->next=NULL;

and this:

root->next=NULL;

do the exact same thing, because temp->next and root->next are the same.

Upvotes: 0

Related Questions