Pointers - > taking the address

Hi all,

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

Regards
Viji R
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

class Doug
{
public:
	int x;
	float b;
};

int main()
{
	Doug d;
	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;
}


Edit - added example
Last edited on
Topic archived. No new replies allowed.