Reputation: 516
I am not getting the difference between an integer a
and *(&a)
? I mean *(&a)
returns the value contained in the address of a
and it's the same as a
, no? So why the use of pointers in this case?
Upvotes: 1
Views: 174
Reputation: 24052
More to the point, you wouldn't normally write *(&a)
, or *&a
. This could arise as a result of macros or something, but you would normally never actually write something like that explicitly. You can take it to extremes: *&*&*&*&*&*&a
works just as well. You can try it for yourself:
#include <stdio.h>
int main()
{
int a = 123;
int b = *&*&*&*&*&*&a;
printf("%d\n", b);
return 0;
}
Upvotes: 0
Reputation: 106012
What is the difference between an integer
a
and*(&a)
?
No difference. int a;
declares a
as a variable of an int
type. &a
is the address of a
is of type int *
, i.e. pointer type and therefore it can be dereferenced. So, *(&a)
will give the value of a
.
Upvotes: 4
Reputation: 5389
Take this as an example,
int a = 1;
int *ptr = &a;
ptr
points to some address in memory, and the address of ptr
itself, is different in memory.
Now, take a look at below drawing,
// *ptr = *(&a)
// Get the adress of `a` and dereference that address.
// So, it gives the value stored at `a`
memory address of a -> 0x7FFF1234
value stored at 0x7FFF1234 = 1
memory address of ptr -> 0x7FFF4321
value stored at 0x7FFF4321 = &a = 0x7FFF1234
+-------+
+------------> 0x7FFF1234 ---->|a = 1 |
| +-------+
| +-----------------+
| | ptr = |
+--*ptr<-------| 0x7FFF1234 [&a] |<--- 0x7FFF4321
+-----------------+
So, there is no difference between both of them, i.e., int a
and *(&a)
are same.
Upvotes: 0
Reputation: 67380
As long as a
is a variable, there's no difference, they're identical.
However, if you use that expression in a macro for instance, it will fail with a compiler error for temporary objects (*&(x+1)
) or literals (*&5
). Perhaps there's a reason for making that distinction in code.
Upvotes: 2