Recursive Pointers

I was talking to someone who was new to low-level languages ​​and manual memory management today, and am doing my best to explain the pointers.

Then he came up with:

#include <stdio.h> int main() { int v = 0; void* vp = &v; int i = 0; for(; i < 10; ++i) { printf("vp: %p, &vp: %p\n", vp, &vp); vp = &vp; } } 

The result of this:

 vp: 0xbfd29bf8, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 vp: 0xbfd29bf4, &vp: 0xbfd29bf4 

This makes no sense to him, as vp should! = & Vp. I am ashamed to say that I do not know what is happening here. So what is going on here?

+4
source share
3 answers

When you have this line in your code

  vp = &vp; 

no wonder vp == &vp ...

In the first iteration, this is how you (and he) expect it.

+7
source

Once this code is run:

 vp = &vp; 

the pointer variable now really stores the address by itself. Please note that this only happens after iterating over the initial loop - the first line is output

 vp: 0xbfd29bf8, &vp: 0xbfd29bf4 

and the values ​​do not yet match, because the above purpose has not yet been fulfilled.

+1
source

This makes no sense to him, as vp should! = & Vp.

Why should this not happen after you have completed this task?

If this helps, try to think of each variable, taking up a numbered place in memory, and a pointer holding one of these numbers with numbered memory. Why should I not point to a void pointer to determine the value that occurs to determine its own location?

+1
source

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


All Articles