简体   繁体   中英

C++ - *p vs &p vs p

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?

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.

I'll give you an example: int q=12; int *p=&q; int *pp; pp=&q;

Technically * and & do not hold anything since they both operate on variables. * will extract the value while & will extract the address. The best way to dig the magic of pointers up is to debug.

          **Adress|Data**
          00001   |12345-----|
          00002   |45678     |
          12345   |99887 <---|-------|
          6757    |33431             |
          9987    |22894<------------|

          Print(&p)----->00001
          Print(p)------>12345
          print(*P)----->99887
          Print(**p)---->22894

What is a POINTER ?

Any variable is located at an adress in the memory and this adress contain a value with a size (some bytes 2 (16bits) , 4 (32 bits) ,8 (64bits)). When the value of this variable is an adresse value, we call this variable a pointer.

I hope this explanation of pointers will help some to understand better. A drawing like this help to understand ++ or -- operator when pointer is moving. The value of the pointer variable is increasing or decreasing so the address the pointer point to (memory cell pointed) is moving up or down in user3231318 representation above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM