C ++ - * p vs & p vs p

I'm still trying to understand the difference between * p, & p and p. In my opinion, * one can think of “value designated”, as well as “address”. In other words, * saves the while value and holds the address. If so, then what is the difference between * p and p? Doesn't p hold the meaning of something like * p?

+4
source share
5 answers

The * operator is used for indirection. Direction means that the value in p interpreted as a memory address and the value is loaded at that address. p is the value of p , and *p is the value stored in the memory location pointed to by p . If you want to indirectly access the value of the integer i , you can point to it the integer point of the pointer ( int *p = &i ) and use this pointer to indirectly change the value of i ( *p = 10 ).

+6
source

Here is a chart.

  & 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 . In the 0xcafebabe memory 0xcafebabe , the value p, p , which is equal to 0xfeedbeef , is 0xfeedbeef . This is also the address *p .

So repeat after me: the p value is the address *p .

And the value of &p is the address of p .

And the value *p is the address **p .

And so on and so forth. So * and & are similar to opposites and *&p == p == &*p if you are not doing funny things with operator overloading.

+4
source

I will give an example: int q=12; int *p=&q; int *pp; pp=&q;

Technically, * and & do not act on anything, since both of them work with variables. * will retrieve the value, and & will retrieve the address. The best way to dig up pointer magic is through debugging. Good luck.

+1
source
  **Adress|Data** 00001 |12345-----| 00002 |45678 | 12345 |99887 <---|-------| 6757 |33431 | 9987 |22894<------------| Print(&p)----->00001 Print(p)------>12345 print(*P)----->99887 Print(**p)---->22894 
0
source

What is a POINTER?

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

I hope this explanation of pointers helps some to understand better. A figure like this helps to understand ++ or - the operator when moving the pointer. The value of the pointer variable increases or decreases, so the address pointed to by the pointer (memory cell) moves up or down in user3231318 above

0
source

Source: https://habr.com/ru/post/1400922/


All Articles