Void pointers in standard-library interfaces
suggest changevoid * is a generic pointer type for object pointers. Any pointer to an object can be converted to or from void * without an explicit cast, and a round trip compares equal to the original pointer.
malloc returns void *, so its result can be assigned directly:
#include <stdlib.h>
int main(void)
{
int *vector = malloc(10 * sizeof *vector);
if (vector == NULL) {
return EXIT_FAILURE;
}
/* Use vector. */
free(vector);
return EXIT_SUCCESS;
}
Do not cast the result of malloc in C. The cast repeats type information and can hide a missing declaration on old implementations. Deriving the element size from *vector also keeps the allocation correct if the pointer's type changes.
Byte-oriented functions use void * so they can accept any object representation:
#include <string.h>
void copy_representation(void)
{
int value = 67;
unsigned char bytes[sizeof value];
memcpy(bytes, &value, sizeof bytes);
}
A void * carries no element type, so it cannot be dereferenced or used for standard pointer arithmetic. Convert it to an appropriately typed pointer before accessing an object, and ensure the resulting access meets the object's alignment, lifetime, and effective-type requirements.
These implicit conversions apply to object pointers, not portably to function pointers.