简体   繁体   中英

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

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}

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.

void * is the generic pointer type. memmove is supposed to manipulate memory regardless of what type of objects are in the memory.

Similarly for memcpy . Compare it with strcpy which uses char * parameters because it's supposed to manipulate strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM