Open In App

Reference to a pointer in C++ with examples and applications

Last Updated : 10 Sep, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Like references to simple data types, we can have references to pointers.




// CPP program to demonstrate references to pointers.
#include <iostream>
using namespace std;
  
int main()
{
    int x = 10;
  
    // ptr1 holds address of x
    int* ptr1 = &x;
  
    // Now ptr2 also holds address of x.
    // But note that pt2 is an alias of ptr1.
    // So if we change any of these two to
    // hold some other address, the other
    // pointer will also change.
    int*& ptr2 = ptr1;
  
    int y = 20;
    ptr2 = &y;
  
    // Below line prints 20, 20, 10, 20
    // Note that ptr1 also starts pointing
    // to y.
    cout << *ptr1 << " " << *ptr2 << " "
         << x << " " << y;
  
    return 0;
}


Output:

20 20 10 20

What is application of above?
Consider a situation where we pass a pointer to a function and we want the function to modify the pointer to point to something else and we want these changes to reflect in caller. For example, writing a linked list function that changes head of it, we pass reference to pointer to head so that the function can change the head (An alternative is to return the head). We can also achieve same thing using double pointers.




// A C++ program to demonstrate application
// of reference to a pointer.
#include <iostream>
using namespace std;
  
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
  
/* Given a reference to pointer to the head of
   a list, insert a new value x at head */
void push(struct Node *&head, int x)
{
    struct Node* new_node = new Node;
    new_node->data = x;
    new_node->next = head;
    head = new_node;
}
  
// This function prints contents of linked
// list starting from head
void printList(struct Node* node)
{
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}
  
/* Driver program to test above functions*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
    push(head, 1);
    push(head, 2);
    push(head, 3);
  
    printList(head);
  
    return 0;
}


Output:

3 2 1


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads