I have a doubt regarding a particular usage in pointer.
In all the books i have seen the below mentioned usage
*(&x) ---> gives the value at x.
So is it correct in using or is it a good practice to use
&(*x) ---> retrieves the address of x
I wrote sample programs, but there were no issues..
Could you please comment whether it is good to use the second one
Both are nonsense if x is a regular pointer. You can just write "x" for both.
*x gives you the value x is pointing at.
x gives you the address of aforementioned value.
&x gives you the address of x.
As Athar said, if x is a pointer, both give the same result. However, if x is a non-pointer variable, the second statement is an error.
In the first statement: &x gives you the address of x, which is a pointer to x. The * operator dereferences the pointer, giving you back the value of x.
In the second statement: *x tries to dereference the pointer x. However, because x is not a pointer, this is an error.
Edit - added example
using namespace std;
d.b = 99.345;
Doug* dp = &d;
Doug e = *(&d);
//Doug e = &(*d);
Doug* ep = *(&dp);
Doug* ep2 = &(*dp);
cout << e.b << endl;
cout << ep->b << endl;
cout << ep2->b << endl;
Last edited on