Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive pointers

Tags:

c

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?

like image 681
Kim Sun-wu Avatar asked Jan 18 '23 17:01

Kim Sun-wu


2 Answers

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.

like image 88
jpalecek Avatar answered Jan 25 '23 05:01

jpalecek


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.

like image 45
sharptooth Avatar answered Jan 25 '23 06:01

sharptooth