Skip to content
Related Articles

Related Articles

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

3 2 1

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :