Back to Blog

C in 100 Seconds: Void Pointers | Episode 30

Daryl WongDaryl Wong

Video: C in 100 Seconds: Void Pointers — Generic Pointers in C | Episode 30 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Void Pointers — Generic Pointers in C

C in 100 Seconds, Episode 30


A void pointer can hold the address of any type. It is the closest thing C has to generics. The tradeoff — you have to cast it back to the right type before you can use the value.

Declaring and Assigning

void *ptr;
ptr = &x;  // x is an int
ptr = &y;  // y is a float
ptr = &z;  // z is a char

One pointer, three different types. void star accepts any address.

Casting to Dereference

You cannot dereference a void pointer directly. Cast it first:

printf("int: %d\n", *(int *)ptr);
printf("float: %.2f\n", *(float *)ptr);
printf("char: %c\n", *(char *)ptr);

The cast tells the compiler how many bytes to read and how to interpret them.

Generic Functions

A function that takes void star can handle any type:

void print_value(void *ptr, char type) {
  if (type == 'i')
    printf("int: %d\n", *(int *)ptr);
  else if (type == 'f')
    printf("float: %.2f\n", *(float *)ptr);
  else if (type == 'c')
    printf("char: %c\n", *(char *)ptr);
}

Pass any address with a type tag. One function, any data.

Where Void Pointers Appear

  • malloc returns void * — you cast it to your type
  • qsort takes void * comparator arguments
  • Generic containers — linked lists, hash maps storing any type
  • Callback data — passing context through void star

Full Code

#include <stdio.h>

void print_value(void *ptr, char type) {
  if (type == 'i')
    printf("int: %d\n", *(int *)ptr);
  else if (type == 'f')
    printf("float: %.2f\n", *(float *)ptr);
  else if (type == 'c')
    printf("char: %c\n", *(char *)ptr);
}

int main() {
  int x = 42;
  float y = 3.14;
  char z = 'A';

  void *ptr;

  ptr = &x;
  printf("int: %d\n", *(int *)ptr);

  ptr = &y;
  printf("float: %.2f\n", *(float *)ptr);

  ptr = &z;
  printf("char: %c\n", *(char *)ptr);

  printf("\nGeneric function:\n");
  print_value(&x, 'i');
  print_value(&y, 'f');
  print_value(&z, 'c');

  return 0;
}

Next episode: Stack vs Heap — where variables live and why it matters.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode30