Why does `memmove` use` void * `as a parameter instead of` char * `?
The definition of the c library function memmove
looks like this:
void* memmove(void *s1, const void *s2, size_t n)
{
char *sc1;
const char *sc2;
sc1 = s1;
sc2 = s2;
...
}
I am wondering why we need to use void*
and const void*
how type of parameters. Why not directly char*
and const char*
?
Update
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}
void *
- general type of pointer. memmove
it is supposed to manipulate memory no matter what type of objects is in memory.
Likewise for memcpy
. Compare it to strcpy
one that uses parameters char *
as it must manipulate strings.
If char*
and are used const char*
, then when calling memmove
for other types, we should always use char*
.
Using void*
and const void*
, we can write shorter code and there is no casting overhead.