I did try searching for this on Stack Overflow, but I think due to the syntax and not knowing exactly what to search I became a little unstuck.
I have seen (v
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.).