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}

Fihop
  • 3,127
  • 9
  • 42
  • 65
  • 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 03 '15 at 04:59

2 Answers2

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.

cshu
  • 5,654
  • 28
  • 44
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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294