Reading history

Generic Programming in C With void Pointers

8 min read 0 views

Write generic C functions and containers with void pointers, item sizes and function-pointer callbacks: generic swap, search and a growable array.

C has no templates or generics. Yet qsort sorts any kind of array, and memcpy copies any kind of data. How? They treat data as bytes behind a void * pointer, and they are told the item size and given a function pointer for anything type-specific, such as comparing. With these three tools you can write your own functions and containers that work for every type.

In this lesson you will learn

  • Why void * can point to anything, and its limits
  • Stepping through an array of unknown type with a byte pointer
  • Writing a generic swap and a generic search
  • Comparison and callback function pointers
  • Building a generic growable array

You should know void pointers, function pointers and qsort.

Generic Swap and Search

#include <stdio.h>
#include <string.h>

/* Swap any two objects of the same size, byte by byte through a buffer */
static void swap_any(void *a, void *b, size_t size) {
    unsigned char tmp[64];             /* enough for the types used here */
    if (size > sizeof tmp) return;
    memcpy(tmp, a, size);
    memcpy(a, b, size);
    memcpy(b, tmp, size);
}

/* Find an item in any array, using a comparison function */
static void *find_any(const void *key, void *base, size_t n, size_t size,
                      int (*cmp)(const void *, const void *)) {
    unsigned char *p = base;           /* char pointer so we can step by bytes */
    for (size_t i = 0; i < n; i++, p += size)
        if (cmp(key, p) == 0)
            return p;
    return NULL;
}

static int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

struct City { char name[16]; int code; };
static int cmp_city_name(const void *key, const void *item) {
    return strcmp((const char *)key, ((const struct City *)item)->name);
}

int main(void) {
    int x = 3, y = 9;
    swap_any(&x, &y, sizeof x);
    printf("ints swapped: x=%d y=%d\n", x, y);

    double p = 1.25, q = 7.5;
    swap_any(&p, &q, sizeof p);
    printf("doubles swapped: p=%.2f q=%.2f\n", p, q);

    struct City c1 = {"Sylhet", 60}, c2 = {"Rangpur", 55};
    swap_any(&c1, &c2, sizeof c1);
    printf("structs swapped: c1=%s c2=%s\n", c1.name, c2.name);

    int marks[] = {72, 95, 58, 88};
    int want = 58;
    int *hit = find_any(&want, marks, 4, sizeof marks[0], cmp_int);
    printf("58 found at index %td\n", hit ? hit - marks : -1);

    struct City cities[] = {{"Dhaka", 10}, {"Khulna", 40}, {"Barishal", 50}};
    struct City *c = find_any("Khulna", cities, 3, sizeof cities[0], cmp_city_name);
    printf("Khulna: %s\n", c ? "found" : "not found");
    struct City *none = find_any("Comilla", cities, 3, sizeof cities[0], cmp_city_name);
    printf("Comilla: %s\n", none ? "found" : "not found");
    return 0;
}

Output

ints swapped: x=9 y=3
doubles swapped: p=7.50 q=1.25
structs swapped: c1=Rangpur c2=Sylhet
58 found at index 2
Khulna: found
Comilla: not found
  • A void * can hold the address of any object. But you cannot dereference it or do arithmetic on it, because C does not know the size of what it points to.
  • swap_any does not need to know the type. It copies size bytes in three steps through a temporary buffer, so the same function swaps ints, doubles and whole structs.
  • find_any walks the array with an unsigned char *, adding size bytes each step to reach the next item. This is what array indexing does behind the scenes.
  • Only the comparison depends on the type, so the caller passes it in as a function pointer. cmp_int turns its void * arguments back into int *; cmp_city_name compares a string key with a struct’s name.
  • (x > y) - (x < y) returns −1, 0 or 1 without the overflow risk of x - y.
  • The search returns a pointer to the match, or NULL. Subtracting the array start gives its index.

A Generic Growable Array

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* A generic growable array: stores items of any one type, by copying bytes */
typedef struct {
    unsigned char *data;
    size_t size;      /* bytes per item */
    size_t count;
    size_t capacity;
} Vec;

static void vec_init(Vec *v, size_t item_size) {
    v->data = NULL; v->size = item_size; v->count = v->capacity = 0;
}

static int vec_push(Vec *v, const void *item) {
    if (v->count == v->capacity) {
        size_t cap = v->capacity ? v->capacity * 2 : 4;
        unsigned char *p = realloc(v->data, cap * v->size);
        if (!p) return -1;
        v->data = p; v->capacity = cap;
    }
    memcpy(v->data + v->count * v->size, item, v->size);
    v->count++;
    return 0;
}

static void *vec_get(const Vec *v, size_t i) {
    return i < v->count ? v->data + i * v->size : NULL;
}

/* Apply a function to every item */
static void vec_each(Vec *v, void (*fn)(void *item)) {
    for (size_t i = 0; i < v->count; i++) fn(vec_get(v, i));
}

static void vec_free(Vec *v) { free(v->data); vec_init(v, v->size); }

typedef struct { const char *name; double price; } Product;

static void add_vat(void *item)  { ((Product *)item)->price *= 1.15; }
static void print_product(void *item) {
    const Product *p = item;
    printf("  %-10s %8.2f\n", p->name, p->price);
}
static void print_int(void *item) { printf("%d ", *(int *)item); }

int main(void) {
    Vec nums;
    vec_init(&nums, sizeof(int));
    for (int i = 1; i <= 10; i++) { int sq = i * i; vec_push(&nums, &sq); }
    printf("%zu ints, capacity %zu: ", nums.count, nums.capacity);
    vec_each(&nums, print_int);
    printf("\n");

    Vec shop;
    vec_init(&shop, sizeof(Product));
    Product items[] = {{"Notebook", 120}, {"Pen", 15}, {"Bag", 1200}};
    for (int i = 0; i < 3; i++) vec_push(&shop, &items[i]);
    vec_each(&shop, add_vat);
    printf("prices with 15%% VAT:\n");
    vec_each(&shop, print_product);

    printf("item 3 is %d; item 50 is %s\n", *(int *)vec_get(&nums, 3),
           vec_get(&nums, 50) ? "present" : "NULL (out of range)");

    vec_free(&nums);
    vec_free(&shop);
    return 0;
}

Output

10 ints, capacity 16: 1 4 9 16 25 36 49 64 81 100 
prices with 15% VAT:
  Notebook     138.00
  Pen           17.25
  Bag         1380.00
item 3 is 16; item 50 is NULL (out of range)
  • Vec remembers the size of one item and stores items as raw bytes. Item i starts at data + i * size.
  • vec_push copies the item’s bytes in with memcpy, doubling the capacity with realloc when full: 4, 8, then 16 for ten ints.
  • vec_get returns a void * to the item, or NULL if the index is out of range. The caller converts it to the right type.
  • vec_each calls a callback for every item. The same function adds VAT to products or prints integers, depending on the function passed in.
  • The same code serves int and Product without any change. That is the point of generic code.

The Price of Generic C

BenefitCost
One implementation for every typeNo type checking: the compiler cannot stop you passing a double to a vector of int
Works with structs of any sizeCallers must pass the correct sizeof
Behaviour customised with function pointersCalls through function pointers are harder for the compiler to optimise

Good habits reduce the risk: store the item size inside the container (as Vec does), name functions clearly, and wrap them in small type-specific helpers when you use them a lot. For choosing a function by argument type at compile time, C11 also has _Generic.

Common Mistakes

  1. Doing arithmetic on a void *. Standard C does not allow it; convert to unsigned char * first.
  2. Casting to the wrong type in a callback, such as reading a double as an int. Nothing checks this for you.
  3. Passing the size of a pointer instead of the size of the item: sizeof p instead of sizeof *p.
  4. Storing pointers to stack variables in a container that outlives them. Vec avoids this by copying the bytes.

Practice Exercises

Exercise 1. Write void *max_any(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *)) that returns a pointer to the largest item.

Show answer
void *max_any(void *base, size_t n, size_t size,
              int (*cmp)(const void *, const void *)) {
    if (n == 0) return NULL;
    unsigned char *best = base, *p = base;
    for (size_t i = 1; i < n; i++) {
        p += size;
        if (cmp(p, best) > 0) best = p;
    }
    return best;
}

Exercise 2. Write a callback for vec_each that doubles every int in a vector.

Show answer
static void double_int(void *item) {
    *(int *)item *= 2;
}
/* vec_each(&nums, double_int); */

Frequently Asked Questions

Do I need to cast malloc’s result in C?

No. In C a void * converts to any object pointer type automatically, so int *p = malloc(n * sizeof *p); is correct. C++ does require the cast, which is why you sometimes see it.

Why use unsigned char * for stepping through bytes?

The standard guarantees that char types can view the bytes of any object, and unsigned char avoids surprises with negative values. Pointer arithmetic on it moves exactly one byte per step.

Summary

  • Generic C code passes data as void *, plus the item size, plus function pointers for type-specific work.
  • Step through items with an unsigned char * and i * size.
  • Copy items with memcpy, and let callbacks decide what to do with them.
  • You gain reuse but lose type checking, so be careful with sizes and casts.

Next: Circular Buffer (Ring Buffer) in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *