Hi there I have a question pertaining to C pointers (especially void *)
I'm working with void * pointers that point to arbitrary blobs of memory that act as cells for a Vector implementation. These blobs are allocated on the heap.
My question is why does assigning
void *dest = CVectorNth(cv, i);
void *src = CVectorNth(cv, i-1);
*(void **)dest = *(void **)src;
not work while
memmove(dest, src, elementSize);
does work.
Why do I need to use memmove? In my head I am changing the value of the pointer to the address the src is pointing to.
I know memmove is the correct way to go, but now I can't even think of a reason why
dest = src;
wouldn't work
because *(void **)dest = *(void **)src; != memmove(dest, src, elementSize); first is just assignment operation where as memmove() copy memory content from src to dest (deep-copy)
Edit
Suppose, your dest and src are something like this ?
src 5 6 7 8
+-----+ +--+--+--+---+
| 5 +----->| A|B |C | D |
+-----+ +--+--+--+---+
dest 18 19 20 21
+-----+ +--+--+--+---+
| 18 +----->| | | | |
+-----+ +--+--+--+---+
Now, what *(void **)dest = *(void **)src; ?
it like
src 5 6 7 8
+-----+ +--+--+--+---+
| 5 +----->| A|B |C | D |
+-----+ +--+--+--+---+
dest 18 19 20 21
+-----+ +--+--+--+---+
| 18 +----->| A| | | |
+-----+ +--+--+--+---+
because by assignment you copy content (because using *) of location 5 into location 18.
Its rough diagram because *(void **)dest = *(void **)src; someting wrong in my understating
consider larsmans's answer here
Whereas, by doing memmove(dest, src, elementSize);:
it like
src 5 6 7 8
+-----+ +--+--+--+---+
| 5 +----->| A|B |C | D |
+-----+ +--+--+--+---+
dest 18 19 20 21
+-----+ +--+--+--+---+
| 18 +----->| A|B |C | |
+-----+ +--+--+--+---+
Suppose elementSize = 3 ,
memmove copy elementSize elements from src to dest pointed memory area (deepcopy)
by dest = src do like:
src 5 6 7 8
+-----+ +--+--+--+---+
| 5 +----->| A|B |C | D |
+-----+ --->+--+--+--+---+
|
dest | 18 19 20 21
+-----+ | +--+--+--+---+
| 5 +--- | | | | |
+-----+ +--+--+--+---+
Shadow copy:
From: Thomas (thanks!)
More specifically, the latter technique is known as "pointer swapping" and does have its uses, but is not directly compatible with deep memory copy (it requires a different design, in particular the two memory areas being "swapped" need to be persistent). For a vector implementation it's unlikely to be of any us
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With