While understanding the double pointer concept and where it should be used,I have a doubt.I had experimented this code and found that i could use pointer passing by reference also instead of double pointers.
#include<iostream>
using namespace std;
void modify_by_value(int* );
void modify_by_refrence(int* &);
int a=4, b=5;
void main()
{
int *ptr = NULL;
ptr = &a;
cout << "*ptr before modifying by value: " << *ptr << endl;
modify_by_value(ptr);
cout << "*ptr after modifying by value: " << *ptr << endl;
cout << "*ptr before modifying by refrence: " << *ptr << endl;
modify_by_refrence(ptr);
cout << "*ptr after modifying by refrence: " << *ptr << endl;
}
void modify_by_value(int* ptr) //this function can change *ptr but not the ptr(address contained) itself;
{
ptr = &b;
}
void modify_by_refrence(int * &ptr) //this function has refrence and hence can modify the pointer;
{
ptr = &b;
}
What's the benefit of using double pointers instead of reference?And where this thing should be used
"Why using reference to pointer instead of pointer to pointer"? You will get the same answer as if asking "why using pointer instead of reference" for any other kind of variable...
Basically:
references (to pointer or any other variable) are smart because there should always be an object behind
pointers (to pointer or any other variable) are smart because they could possibly be NULL
(optional)
references (to pointer or any other variable) are not available in C
references (to pointer or any other variable) are smart because they can be used as objects (no need to dereference like pointers, easier syntax, rading)
etc...
There are many posts answering this question already:
What are the differences between a pointer variable and a reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With