Skip to content
AgileLogics
5 min read

Void Pointers & Generic Programming

Prerequisites: Function pointers & callbacks

A void * points to memory of an unspecified type — it's how C approximates the "works with any type" flexibility that languages like Java get from generics, at the cost of losing compile-time type checking on that pointer until it's cast back.

void printAsInt(void *data) {
    int *p = (int *) data;
    printf("%d\n", *p);
}

int main(void) {
    int x = 42;
    printAsInt(&x); // 42
    return 0;
}

This is exactly how qsort and bsearch work with an array of any element type — they operate on void * and an element size, trusting the caller to cast correctly inside the comparison function.

Common mistakes

  • Casting a void * back to the wrong type — the compiler can't catch this for you, since void * deliberately erases the original type information.