The definition of the c library function memmove
is like the following:
void* memmove(void *s1, const void *s2, size_t n)
{
char *sc1;
const char *sc2;
sc1 = s1;
sc2 = s2;
...
}
I'm wondering why do we need to use void*
and const void*
as the parameters' type. Why not directly char*
and const char*
?
int test_case[] = {1, 2, 3, 4, 5, 6, 7, 8, 10};
memmove(test_case+4, test_case+2, sizeof(int)*4);
Output: test_case = {1, 2, 3, 4, 3, 4, 5, 6, 10}
If char*
and const char*
are used, then we have to always cast to char*
when invoking memmove
on other types.
By using void*
and const void*
, we are able to write shorter code, and the casting has no performance overhead.
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