Today when I was reading others' code, I saw something like void *func(void* i);
, what does this void*
mean here for the function name and for the variable type, respectively?
In addition, when do we need to use this kind of pointer and how to use it?
Best Answer
A pointer to
void
is a "generic" pointer type. Avoid *
can be converted to any other pointer type without an explicit cast. You cannot dereference avoid *
or do pointer arithmetic with it; you must convert it to a pointer to a complete data type first.void *
is often used in places where you need to be able to work with different pointer types in the same code. One commonly cited example is the library functionqsort
:base
is the address of an array,nmemb
is the number of elements in the array,size
is the size of each element, andcompar
is a pointer to a function that compares two elements of the array. It gets called like so:The array expressions
iArr
,dArr
, andlArr
are implicitly converted from array types to pointer types in the function call, and each is implicitly converted from "pointer toint
/double
/long
" to "pointer tovoid
".The comparison functions would look something like:
By accepting
void *
,qsort
can work with arrays of any type.The disadvantage of using
void *
is that you throw type safety out the window and into oncoming traffic. There's nothing to protect you from using the wrong comparison routine:compareInt
is expecting its arguments to be pointing toint
s, but is actually working withdouble
s. There's no way to catch this problem at compile time; you'll just wind up with a missorted array.