
copying the content of a void-pointer to another void-pointer?
Quote:
>Hi.
>I would like to know how to copy the contents of a void-pointer to
>another void-pointer. We tried something like:
>for(i=0; i < 20; i++)
> *(ptr1+i) = *(ptr2+i);
Thanks to recent advances in the C language you can now use the following
notation:
ptr1[i] = ptr2[i];
Unfortunately, pointer arithmetic on, and dereferencing of, void * pointers
are invalid operations, regardless of how they are expressed. Assuming that you
want to copy individual bytes, you can convert the pointers to unsigned char *
and then do a byte by byte copy using the above loop:
unsigned char *ucp1 = ptr1, *ucp2 = ptr2;
/*...*/
for (i = 0; i < 20; i++)
ucp1[i] = ucp2[i];
There is a revolutionary new library function called memcpy() which
does the above using void * pointers:
#include <stdlib.h>
/*...*/
memcpy(ptr1, ptr2, 20); /* WOW! */