I am still struggling to understand the difference between *p, &p, and p. From my understanding, * can be thought of "value pointed by", and & as "adress of". In other words, * holds the value while & holds the adress. If this is true, then what is the distinction between *p and p? Doesn't p hold the value of something, just like *p?
*p is a pointer, means it holds an address of a value or a block of reserved memory, It can access upto one level. It is used if you want to retain a block of memory where your values are in.
In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative.
(void*)&p means the address of p. (void*)p means the contents of p (in this case the address of num ). (void*)*p means the contents of what the variable p points to ( 12 ) (value of num ). See http://www.c4learn.com/c-programming/c-pointer-address-operator/ for more details about the address operator.
The * operator is used for indirection. Indirection means the value in p is interpreted as a memory address and the value at that address is loaded. p is the value of p while *p is the value stored in the memory location pointed by p .
The *
operator is used for indirection. Indirection means the value in p
is interpreted as a memory address and the value at that address is loaded. p
is the value of p
while *p
is the value stored in the memory location pointed by p
. When you want to indirectly access the value of an integer i
, you can have an integer pointer point to it (int *p = &i
) and use that pointer to modify the value of i
indirectly (*p = 10
).
Here is a diagram.
&p=0xcafebabe p=0xfeedbeef *p=0xdeadbeef <-- memory address +--------------+ +---------------+ +----------------+ | p=0xfeedbeef | -> | *p=0xdeadbeef | -> | **p=0x01234567 | <-- memory contents +--------------+ +---------------+ +----------------+
So, &p
is the address of p
, which is 0xcafebabe
. The memory location 0xcafebabe
stores the value of p, p
, which is 0xfeedbeef
. That is also the address of *p
.
So repeat after me: The value of p
is the address of *p
.
And, the value of &p
is the address of p
.
And, the value of *p
is the address of **p
.
And so on and so forth. So *
and &
are like opposites, and *&p == p == &*p
, unless you do funny things with operator overloading.
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