Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `memmove` use `void *` as parameter instead of `char *`?

Tags:

c

memmove

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*?

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}

like image 696
Fihop Avatar asked Dec 24 '22 16:12

Fihop


1 Answers

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.

like image 175
cshu Avatar answered Jan 09 '23 03:01

cshu