5

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}

1
  • 2
    Because this isn't a string function but a memory one; using void* makes it Works with any kind of pointer and not char* ones.
    – Jack
    Aug 3, 2015 at 4:59

2 Answers 2

6

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.

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.