would it be OK if the function was: void memcpy(char* dst, const char* src, size_t size)?
What is the advantage of using void pointers in memcpy()?
Before the void data type was added in the 1989 standard, that was how functions like memcpy were designed. char * was the closest thing to a "generic" pointer at the time.
The problem is that if memcpy still used char * arguments and you wanted to call memcpy on a target that wasn't an array of char, you would have to explicitly cast the pointer value:
int foo[N];
int bar[N];
...
memcpy( (char *) foo, (const char *) bar, N * sizeof *foo );
because you can't assign pointers of one type to another type without a cast. This wasn't (as much of) a problem in pre-ANSI C because you didn't have function prototypes; that is, the compiler didn't check that the number and types of arguments in the function call matched the definition, but it's definitely an issue now.
However, unlike other object pointer types, you can assign any T * value to void * and back again without needing the cast, so the memcpy call can be written as
memcpy( foo, bar, N * sizeof *foo );
I remember the pre-standardization days (although I was still in college). Casting gymnastics weren't fun. Embrace the void * type, because it is saving you some heartburn.
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