Kim Sun-wu
Kim Sun-wu

Reputation: 1648

Recursive pointers

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?

Upvotes: 4

Views: 555

Answers (3)

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

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?

Upvotes: 1

sharptooth
sharptooth

Reputation: 170499

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.

Upvotes: 1

jpalecek
jpalecek

Reputation: 47762

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.

Upvotes: 7

Related Questions