Search code examples
cpointersvoid-pointers

Why does memchr() take a void pointer as input?


I'm currently reprogramming some C libraries. So my question is: Why does memchr take an const void *s pointer and not simply an character pointer?

I see that you could probably search for other stuff, but the function is literally called memchr so why use a void pointer?

Thanks in advance!


Solution

  • C’s early development involved a fair amount of treating things as individual bytes and allowing programmers access to the bytes that represented objects. The name memchr reflects that history and cannot readily be changed now.

    void was added to the language to provide a type that represents, in a sense, “something is there, but this is flexible.” The first parameter to memchr has type const void * because the routine may be used to search for a byte in any type of object, not necessary an object that is primarily an array of characters.