Archives: February 2012

Void pointers in C

Void pointers are pointers pointing to some data of no specific type.

A void pointer is defined like a pointer of any other type, except that void* is used for the type:

void *pt;

You can’t directly dereference a void pointer; you must cast it to a pointer with a specific type first, for instance, to a pointer of type int*:

*(int*)pt;

Thus to assign a value to a void pointer, you will have to do something like:

*(int*)pt=42;
*(float*)pt=3.14; /* You can assign a value of any type to the pointer */

The use of void pointers is mainly allowing for generic types. You can create data structures that can hold generic values, or you can have functions that take arguments of no specific type. If you wanted a linked list allowing for generic values, you would define your list node like this:

struct ListNode{
  struct ListNode *next;
  void *data;
};

A generic function for doubling a value might look like the following:

#define TYPE_INT 0
#define TYPE_FLOAT 1
void doubleVal(int type, void *var){
  if(type==TYPE_INT){
    *(int*)var*=2;
  } else if(type==TYPE_FLOAT){
    *(float*)var*=2;
  }
}

Called, rather obviously, like the following:

doubleVal(TYPE_INT, &integer);
doubleVal(TYPE_FLOAT, &floatingPoint);

You can’t perform pointer arithmetic on void pointers since the compiler doesn’t know the size of the data which is pointed to, however, you may cast a void pointer to a pointer of some other type and perform pointer arithmetic on that.