What is (void*) casting used for?

void*, usually referred to as a void pointer, is a generic pointer type that can point to an object of any type. Pointers to different types of objects are pretty much the same in memory and so you can use void pointers to avoid type checking, which would be useful when writing functions that handle multiple data types.

Void pointers are more useful with C than C++. You should normally avoid using void pointers and use function overloading or templates instead. Type checking is a good thing!


A void pointer is a pointer to a value whose type and size are unknown. I'll give an example of how it might be used in C - although other commenters are correct in saying that it by and large shouldn't be used (and, in fact, isn't necessary) in C++.

Suppose you have a struct which stores a key and a value. It might be defined like this:

typedef struct item_t
{
    char *key;
    int value;
} item_t;

So you could use this structure to match up any string key with an integer value. But what if you want to store some arbitrary value? Maybe you want some keys to match up with integers, and some keys to match up with doubles? You need to define your struct in such a way that it will keep track of (with a pointer) a value of arbitrary type and size. The void * fits the bill in this case:

typedef struct item_t
{
    char *key;
    void *value;
} item_t;

Now, if your value is an int, you can get at its value using (int *) value, or if its value is a double, you can do it using (double *) value. This assumes, of course, that the code using the struct knows what type it expects to see in what context.

In C++, though, this same functionality is usually achieved not through the use of void *, but by using things like templates or a superclass which all of your different types descend from (like Object in Java, for example - a list of Objects can store some String's, some Integer's, etc.).