Himanshu Ranjan
Himanshu Ranjan

Reputation: 47

How pointer reference works in C++?

I have 3 pointers:

Node* head;
Node* temp=head;
Node* p=new Node(2);

Now I assign:

temp->next=p

Will the next of head will also be changed?

head->next=?

Upvotes: 1

Views: 69

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117328

Yes, if head would actually point at some allocated memory, temp would point to the same memory.

Example:

#include <iostream>

struct Node {
    Node(int X) : x(X) {}
    int x;
    Node* next;
};

int main() {
    Node* head = new Node(1);

    Node* temp = head;                     // temp points to the same memory as head

    Node* p = new Node(2);
    temp->next = p;                        // head->next is the same as temp->next

    std::cout << head->next->x << '\n'     // prints 2

    delete head;
    delete p;
}

Upvotes: 1

Related Questions