Reputation: 860
I'm learning C and C#. I'm learning about pointers and don't know what it means to combine the indirection operator and the address operator. What does it mean to combine the two?
Here is an example:
int *p, *q;
p = *&q;
Upvotes: 0
Views: 94
Reputation: 400029
It means what it must mean. :)
If you read it from left to right, the right hand side simply means "the value retreived by following the pointer whose value is the address of q
".
It's the same as p = *(&q);
, and thus it's the same as p = q;
.
I didn't even notice, but your program is wrong to declare p
and q
to be pointers. That won't compile, it should be:
int p, q;
p = *&q;
Also, this might be a bit ill-defined since q
is never assigned a value before being read, not 100% sure about that.
Upvotes: 3
Reputation: 3489
&
can be thought of as an address of (<something>)
operator. So &q
is address of q. Now *
can be thought of as an value at (<something>)
operator. So *q is basically the value stored at the address contained in q, i.e, *
treats the variable as always containing an address. Now *&q, by associativity is *(&q). Which means
value stored at (address of q)
which is same as value stored at q
address of q will be having another address since q is a pointer. So it is the same as
p=q
Upvotes: 3
Reputation: 9311
Your example would set pointer p to the value of pointer q. It does nothing to the values pointed by p and q. It just sets the variable p, to the value of variable q, which both happen to be pointers to integer values. Lets see some examples:
*p = *q; // the value at the address pointed by q, gets copied to the address, pointed by p
p = &q; // this is illegal, since the type of &q is int ** (pointer to a pointer to an integer), but the type of p is int *
Upvotes: 0
Reputation: 55937
&q;
would give you the address of the variable q, that is it's a pointer to q we could write
int ** pointerToQ = &q;
if we then say
*pointerToQ
we are asking for whater ever pointerToQ points to, which is q itself. So
*&q
Just gets us back to q.
Upvotes: 0