Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 135 ยท Pointers

void Pointers and Generic Code

Learn how C's void * holds any object address, how memcpy and qsort use it to work on any type, how to write generic functions safely, and what C23 typeof adds.

Every pointer you've met so far has a type: an int * points to an int, a char * to a char. That type tells the compiler how many bytes to read when you dereference and how far to move when you add 1. But some functions don't care what they're pointing at. memcpy copies bytes, whatever they mean. qsort sorts arrays of anything. malloc hands out memory before you've decided what to put in it. For those, C has the generic pointer type void *: "a pointer to something, type unknown".

void * is how C does generic programming without templates or classes. It's powerful and it's also the place where C stops checking your types, so it has to be used with discipline. In this lesson you'll learn what you can and can't do with a void *, how to write your own generic functions in the style of memcpy and qsort, how callbacks receive extra context, and how C23's typeof lets macros be generic and type-safe.

This lesson uses function pointers in a few examples; skim that lesson first if they're new to you.

What void * can hold

Any object pointer converts to void * and back again without a cast, and the round trip gives you the original pointer. That's what makes void * a universal container for addresses:

C One void pointer, many types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Two operations are missing on purpose:

  • You can't dereference a void *. *any has no meaning, because the compiler doesn't know whether to read 1, 4 or 8 bytes. You must convert to a real pointer type first, either by assigning to a typed pointer or with a cast like *(char *)any.
  • You can't do arithmetic on a void * in standard C, for the same reason: any + 1 would need the element size. GCC allows it as an extension (treating the size as 1), but portable code converts to char * or unsigned char * first.

Note: In C, void * converts to other object pointers implicitly. That's why int *p = malloc(10 * sizeof *p); needs no cast. C++ requires a cast here, which is why you see (int *)malloc(...) in code meant for both languages. In pure C, leave the cast out: it adds clutter and, in old C, could hide a missing #include <stdlib.h>. See C and C++ for more differences.

Keeping track of the real type

A void * forgets the type, so you must remember it. Converting it back to the wrong type and dereferencing is undefined behavior: reading a double through an int * may give garbage, and the optimizer is allowed to assume it never happens (the strict aliasing rule). A common pattern is to carry the type next to the pointer:

C A void pointer with a type tag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The kind argument and the void * must agree, and nothing but your own care enforces that. Pass KIND_DOUBLE with &year and the function reads 8 bytes from a 4-byte int. Notice the const void *: it works just like const int *, promising the function only reads. Unions shows a tidier way to bundle a type tag with its data.

Generic code that works on bytes

The safest kind of generic code doesn't need to know the type at all, because it treats every object as a sequence of bytes. C explicitly allows accessing any object's bytes through unsigned char * (or char *). Give a function the address and the size, and it can copy, compare, swap or clear any object. This is exactly how memcpy, memmove, memcmp and memset work.

C A generic swap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The functions take void * so callers can pass any address without a cast, then immediately convert to unsigned char * to do arithmetic. The size parameter is essential: without it the function couldn't know where the object ends. Always pass sizeof of the actual object, never a hard-coded number.

If you call swap_any(&i1, &d1, sizeof d1) with mismatched types, it compiles without a warning and corrupts memory. That's the price of void *: the compiler has given up checking. The typeof section below shows how to get the checking back for simple cases.

Generic algorithms: element size plus a callback

To compare elements, byte-wise code isn't enough. "Is 10 less than 9?" depends on whether the bytes are an int, a double or a string. The standard library's answer is to pass a comparison function. Here's the prototype of qsort from <stdlib.h>:

C
void qsort(void *base, size_t count, size_t size,
           int (*compare)(const void *a, const void *b));

base is the array, count the number of elements, size the size of each one, and compare a function that receives pointers to two elements and returns a negative number, zero or a positive number. qsort moves elements around by bytes; only compare knows the real type.

You can write your own algorithms in the same style. This generic linear search finds the first element equal to a key and works for any element type:

C A qsort-style generic search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Study compare_strings closely, because it's the most common qsort bug. The array holds const char * elements, so the comparator receives a pointer to an element, which is a pointer to a const char *. You must dereference once to get the string. Casting the argument straight to const char * and passing it to strcmp compiles fine, but compares the bytes of the pointers themselves.

compare_ints returns (x > y) - (x < y) instead of the tempting x - y. The subtraction overflows for values far apart (for example INT_MIN - 1), which is undefined behavior and can flip the sign of the result.

find_first returns void * even though its base is const void *, the same compromise bsearch and strchr make. The cast (void *)element discards const so callers with writable arrays get a writable pointer back. qsort and bsearch covers sorting by several keys and searching sorted arrays.

Passing context to a callback

Sometimes a callback needs extra data: a threshold, a counter, an output file. C libraries solve this with one more void * parameter, often called context or user_data, that the library passes through untouched:

C A callback with a context pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

for_each doesn't know or care what context points to. collect receives a struct stats, print_one receives a string, and each callback converts the pointer back to the type it expects. You'll see this exact pattern in thread libraries (pthread_create passes a void * to the new thread), GUI toolkits and event loops. Structs and the -> operator are explained in Structures and Structures and Pointers.

Type-safe generic macros with C23 typeof

Byte-wise functions like swap_any can't detect a type mismatch. For small operations, a macro can do better, because a macro sees the actual expressions you pass in. C23 standardizes typeof, which gives the type of an expression (GCC and Clang have offered it as __typeof__ for decades):

C A swap macro with typeof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The temporary gets exactly the type of a, so no bytes are copied blindly, and swapping an int with a double triggers the static_assert at compile time. (Without the assert, the conversion would silently truncate.) C23 also adds typeof_unqual, which drops qualifiers like const, handy when you want a writable copy of a const value. Both work on our compiler with -std=c23; for older compilers, GCC and Clang accept __typeof__. The do { ... } while (0) wrapper is explained in Macros, and _Generic, another tool for type-generic code, is covered there too.

Rules to remember

  • void * holds object pointers only. Function pointers are a separate family; converting a function pointer to void * isn't allowed by standard C (POSIX permits it for dlsym). Use a generic function pointer type such as void (*)(void) instead.
  • void * doesn't carry a size or a type. Every generic function needs a size (or count and size) argument, and every caller must pass matching information.
  • Convert to unsigned char * for byte-level work and to the real type for value-level work. Never access an object through an unrelated type like int * for a double.
  • Keep const: take const void * for input-only buffers, as memcpy does for its source.

Don't reach for void * first. A function that takes const int * is checked by the compiler on every call; one that takes const void * is not. Use void * when you really need one function to serve many types, such as containers, sorting, memory utilities or callback contexts, and keep typed wrappers around it where you can. Building a Dynamic Array shows a generic container built this way.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given double d = 2.5; void *v = &d;, which expression correctly reads the value?

    A void * can't be dereferenced. Convert it back to the original pointer type first. *(int *)v reads the bytes as the wrong type, which is undefined behavior.
  2. 2. Why does a generic function like swap_any(void *a, void *b, size_t size) need the size parameter?

    void * has no element type, so the function can't know how many bytes to swap. sizeof *a doesn't even compile for a void pointer.
  3. 3. An array is const char *names[] = {...}; and you sort it with qsort. What does the comparator's const void *a point to?

    qsort passes pointers to elements. The elements are pointers, so each argument is a pointer to a pointer, and you dereference once to reach the string.
  4. 4. In C, which line compiles without a warning?

    malloc returns void *, which converts implicitly to int * in C. Arithmetic on void * and dereferencing it are not standard, and function pointers don't convert to void *.
  5. 5. What does typeof(a) tmp = (a); do in C23 when a is a double?

    typeof(expression) names the type of the expression, so the declaration creates a double copy of a. That lets macros create correctly typed temporaries.

Summary

  • void * is a generic object pointer: any object pointer converts to it and back implicitly in C, with no cast needed (malloc's result included).
  • You can't dereference a void * or do arithmetic on it in standard C; convert to a typed pointer or unsigned char * first.
  • A void * forgets the type and size, so pair it with a type tag or a size argument, and convert back to the correct type only.
  • Byte-wise generic functions (memcpy, a generic swap) work on any object through unsigned char *.
  • qsort-style algorithms take base, count, size and a comparison callback; comparators receive pointers to elements.
  • A void *context parameter lets callbacks receive extra data without the library knowing its type.
  • C23 typeof (and typeof_unqual) lets macros create correctly typed temporaries, restoring type checking that void * gives up.

Next: Pointers and Functions