A void pointer is a "generic" type of pointer. A void * can be converted to any other type of pointer without an explicit cast. You cannot cast void * or do pointer arithmetic with it; you must first convert it to a pointer to the full data type.
It is used in those places where you need to work with different types of pointers in the same code. One common example is the qsort library function:
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
base is the address of the array, nmemb is the number of elements in the array, size is the size of each element, and compar is a pointer to a function that compares two elements of the array. It is called like this:
int iArr[10]; double dArr[30]; long lArr[50]; ... qsort(iArr, sizeof iArr/sizeof iArr[0], sizeof iArr[0], compareInt); qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareDouble); qsort(lArr, sizeof lArr/sizeof lArr[0], sizeof lArr[0], compareLong);
The array expressions iArr , dArr and lArr implicitly converted from array types to pointer types in a function call, and each of them is implicitly converted from a "pointer to int / double / long " to "pointer to void ".
The comparison functions look something like this:
int compareInt(const void *lhs, const void *rhs) { const int *x = lhs;
By accepting void * , qsort can work with arrays of any type.
The disadvantage of using void * is that you drop type protection from the window and into the oncoming traffic. There is nothing to protect you from the wrong comparison procedure:
qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareInt);
compareInt expects its arguments to point to int s, but actually works with double s. It is not possible to catch this problem at compile time; you just end up with an incorrectly sorted array.