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* p开发者_StackOverflowtr2 = &ptr1;
too.
Please let me know whats the mistake here.
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 http://img705.imageshack.us/img705/2433/pointers.png
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;
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
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.
This is what happens :
You have to manually update ptr1
- it's a variable completely unrelated to ptr2
and they change values independently.
精彩评论