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!
CodePudding user response:
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.
CodePudding user response:
It's the same reason why other functions declared in string.h
use void*
: to avoid a cast.
Maybe you're right, the name is misleading, especially considering its it's part of string.h
. Then again, so is memmove
, memcmp
, memset
, etc...
CodePudding user response:
Before the void
data type was introduced in the 1989 standard (-std=c89
), functions like memchr()
used to take const char *
, because that was the closest thing to a generic pointer at the time.
If const char *
was present today, you will need to cast from x *
to const char *
.
You can also understand this using analogy:
strcpy()
-> string copymemcpy()
-> memory (binary) copy