Learn C
#include "pointersmemory/void_pointers.h"

void Pointers & Generic Code in C

#concept

void* is a pointer to unknown type — it holds any object address but forbids dereferencing and arithmetic until cast back to a concrete type. This is C's generics mechanism: qsort, callbacks with context, and container libraries all traffic in void* to stay type-agnostic.

The contract is bookkeeping by the programmer: whoever casts back must cast to the right type (the compiler can't verify), and arithmetic needs a concrete cast first (char* for byte stepping, the GNU extension aside). void* carries addresses, never type information.

#how it works
1

Holds anything, knows nothing

void *p = &x; compiles for any object pointer — but *p and p++ are illegal until p becomes a concrete pointer type again.

2

Cast back to use

*(int *)p reads the int — the cast documents the programmer's knowledge the compiler cannot check.

3

Generic interfaces run on it

qsort comparators receive const void*; callback context travels as void* — one signature serving every type.

4

No arithmetic without casting

Step bytes via (char *)p + n after casting — void has no size, so the compiler can't scale the step.

#example
#include <stdio.h>
 
void print_int(void *p) {
printf("%d\n", *(int *)p);
}
 
int main(void) {
int x = 42;
print_int(&x);
return 0;
}
Output
42
1&x converts implicitly to void* at the call — any object address fits.
2Inside, *(int *)p casts back to the true type before dereferencing — correct only because the caller really passed an int.
342 prints — generic transport, type-specific interpretation.
#use cases
qsort/bsearch comparators receiving elements as const void*
Callback context pointers smuggling state through generic APIs
Heterogeneous collections storing addresses with external type tags
malloc's return type — void* converting implicitly to any object pointer

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.