tags:

views:

137

answers:

5
void* ptr1 = NULL;
void* ptr2 = ptr1;
unsigned int *buf = data;//some buffer

//now
ptr2 = buf + 8;

The above change in address of ptr2 is not reflected in ptr1. I am trying void* ptr2 = &ptr1; too.

Please let me know whats the mistake here.

+7  A: 

Why would ptr1 follow ptr2?

If you wanted ptr1 to have the same address as ptr2 then you would set it to ptr2:

ptr1 = ptr2;

In your post ptr1 still points to NULL. So you need to explicitly tell it to point to ptr2.

Drawing pictures makes it all the more clearer so go at it:

alt text

Right now you have 2 pointers pointing at some data or no data (NULL). If you want a pointer to follow another pointer, you want a pointer to a pointer (2 asterisks) not just a pointer (1 asterisk).

void** ptr1  = (void**) &ptr2;
JonH
Note that pt2 actually points to buf+8 and so I am no artist, picture doesnt show the actual memory :).
JonH
+1, for being faster than me.
David V.
+4  A: 

A pointer points to an object. Changing a pointer means making it point elsewhere. It does not alter the pointed-to object, nor does it impact any other pointer to that object.

Here, you have ptr1 and ptr2 which are independent variables, each containing a pointer value. If you want changes to one being reflected on the other, then you actually do not want two independent variables, you want just one, and use it several times.

Thomas Pornin
+2  A: 

You have to manually update ptr1 - it's a variable completely unrelated to ptr2 and they change values independently.

sharptooth
+4  A: 

If you want ptr1 to follow ptr2:

void* ptr2 = NULL;
void** ptr1 = (void **)&ptr2;
unsigned int *buf = data;//some buffer

//now
ptr2 = buf + 8;

Now *ptr1 follows ptr2

kumar
+3  A: 

This is what happens :

This is what happens

David V.
@JonH, I had not seen your "idea" when I took the time to draw this. (which is quite obvious by the way, quite pretentious of you to imagine I had to copy your idea to come up with that.) Since you seem upset about this, I've upvoted your reply.
David V.
@David V. - Does look better then mine +1.
JonH
@JonH, if you intended to +1 my response, you actually forgot to :)
David V.
Thanks for ur replies! made it more clear :)
kartik
@David V., What did you use to draw this? Neat!
Vulcan Eager
@Agnel Kurian, I used inkscape ( www.inkscape.org )
David V.