Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 10 Sep, 2018

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

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

// 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;
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);
    return 0;
3 2 1

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!