I was talking to someone who was new to low level languages, and manual memory management today and doing my best to explain pointers.
He then 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 output of this is:
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
Which makes no sense to him as vp should != &vp. I'm ashamed to say that I don't know what's going on here.. so, what's going on here?
When you have this line in code
vp = &vp;
it's no surprise that vp == &vp
...
In the first iteration, it is as you (and he) expect.
Once this code has run:
vp = &vp;
the pointer variable now indeed stores address of itself. Note that this only happens after the initial loop iteration - the first line output is
vp: 0xbfd29bf8, &vp: 0xbfd29bf4
and values are not the same yet because the assignment above has not yet been done.
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