Memory & Pointers

the void pointer

/ void: voyd /

Most pointers carry a type — int *, char *, double * — that says what they point at. Sometimes you want a pointer that can hold the address of anything, without committing to what kind of thing it is. The void pointer, written void *, is exactly that: a generic, typeless pointer, an address with no pointee type attached.

A void * can be assigned the address of any object, and any object pointer can be assigned back to it, in C with no cast needed — that is what makes it the language's universal currency for 'here is a block of memory' without saying what lives there. malloc() returns a void * precisely because it does not know or care what you will store; you assign it to a typed pointer and it converts. But there is a price for being typeless: you cannot dereference a void * (there is nothing to say how many bytes to read), and you cannot do pointer arithmetic on it (no element size to scale by). To use the data you must first convert it to a concrete pointer type, which restores both abilities.

The void pointer is how C writes code that works for any type: generic containers, callbacks that carry a user-supplied context, and functions like qsort() and memcpy() that move or compare raw bytes. The honest caveat is that it throws away type checking — once an address becomes a void *, the compiler can no longer tell you that you converted it back to the wrong type, so a careless conversion can reinterpret bytes as the wrong kind of object with no warning. void * is a deliberate, powerful escape from the type system; treat it as something to use sparingly and convert back carefully.

void *raw = malloc(sizeof(int)); int *n = raw; *n = 42; — malloc hands back a void *, you convert it to int *, and only then can you dereference. You cannot do *raw or raw + 1 while it is still void *.

void * holds any address but must be converted to a typed pointer to use.

void * means 'a pointer to something unspecified', which is different from a null pointer ('a pointer to nothing'). Converting through void * silently discards type checking, so a wrong conversion reinterprets the same bytes as the wrong type with no warning — a real source of subtle bugs.

Also called
generic pointeruntyped pointer通用指標