4

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?

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hmn, I didn't realize &vp decayed to vp? Why doesn't it do so in the printf?
@KimSun-wu: It doesn't decay.
&vp does not decay to vp. What that assignment does is it stores the address of vp in vp (the RAM cell belonging to vp). So, at address 0xbfd29bf4 you have the value 0xbfd29bf4.
Ah. Doh. Obviously, this isn't what he was asking, he just wrote the code wrong, and I was too stupid to see it.
1

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.

Comments

1

Which makes no sense to him as vp should != &vp.

Why shouldn't it, after you've made that assignment?

If it helps, try thinking of every variable as occupying a numbered location in memory, and a pointer as holding one of those numbered memory location. Why shouldn't a void pointer be able to store a value that happens to identify its own location?

1 Comment

What he was actually asking was if he could recursively get pointers to the original pointer (i.e, void****..). I had a brain fart and assumed that's what the above code was doing, my bad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.