Thursday, August 5, 2010

c++: generic pointers and void *

When a variable is declared as being a pointer to type void it is known as a generic pointer. A pointer to void can store an address to any data type. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer.
This is very useful when you want a pointer to point to data of different types at different times.
Here is some code using a void pointer:
int main()
{
    int i;
    char c;
    void *the_data;

    i = 6;
    c = 'a';

    the_data = &i;
    printf("the_data points to int %d\n", *(int*)the_data);

    the_data = &c;
    printf("the_data points to char %c\n", *(char*) the_data);

    return 0;
}
source

No comments: