Monday, March 21, 2016

Void Pointers

You must have noticed that a pointer always holds an address of the same data type, like an integer, pointer always holds the address of integer type of variable, float of a float, double of a double etc.
But there is a special type of pointer called void pointer also known as generic pointer. This type of pointer can hold the memory address of any kind of data type or any object even functions too! This is declared like below:
void *void_ptr = &i;
But the only thing you need to remember is that you can’t dereference a pointer directly. You have to typecast it before you use it. Like if you want to print the value of the above declared void pointer, the memory address it contains point to is:
printf(“%d”,*(int *)void_ptr);
This is very useful when you want a pointer to point to data of different data types at different times.

No comments: