Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - *p vs &p vs p

Tags:

c++

pointers

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?

like image 740
Jon Avatar asked Mar 12 '12 03:03

Jon


People also ask

What is the value of * p in C?

*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.

What does * p mean in C programming?

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.

What is the difference between * P and &P in C?

(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.

Is * p and p * are same C++?

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 .


2 Answers

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).

like image 142
perreal Avatar answered Oct 05 '22 08:10

perreal


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.

like image 26
Dietrich Epp Avatar answered Oct 05 '22 07:10

Dietrich Epp