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.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int * ptr1 = &x;
int *& ptr2 = ptr1;
int y = 20;
ptr2 = &y;
cout << *ptr1 << " " << *ptr2 << " "
<< x << " " << y;
return 0;
}
|
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.
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node *&head, int x)
{
struct Node* new_node = new Node;
new_node->data = x;
new_node->next = head;
head = new_node;
}
void printList( struct Node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
}
int main()
{
struct Node* head = NULL;
push(head, 1);
push(head, 2);
push(head, 3);
printList(head);
return 0;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...