Void Pointers : General Purpose Pointer in C Programming
In the previous chapter we have learnt about dereferencing of pointer variable. In this chapter we will be looking special type of pointer called void pointer or general purpose pointer.
Void Pointers in C Programming : Definition
- Suppose we have to declare integer pointer,character pointer and float pointer then we need to declare 3 pointer variables.
- Instead of declaring different types of pointer variable it is feasible to declare single pointer variable which can act as integer pointer,character pointer.
General Purpose Pointer Variable is Called as Void Pointer
Void Pointer Basics :
- In C General Purpose Pointer is Called as void Pointer.
- It does not have any data type associated with it
- It can store address of any type of variable
- A void pointer is a C convention for a raw address.
- The compiler has no idea what type of object a void Pointer “really points to.” ?
Declaration of Void Pointer :
void * pointer_name;
Void Pointer Example :
void *ptr; // ptr is declared as Void pointer char cnum; int inum; float fnum; ptr = &cnum; // ptr has address of character data ptr = &inum; // ptr has address of integer data ptr = &fnum; // ptr has address of float data
Explanation :
void *ptr;
- Void pointer declaration is shown above.
- We have declared 3 variables of integer,character and float type.
- When we assign address of integer to the void pointer, pointer will become Integer Pointer.
- When we assign address of Character Data type to void pointer it will become Character Pointer.
- Similarly we can assign address of any data type to the void pointer.
- It is capable of storing address of any data type
Summary :
Scenario | Behavior |
---|---|
When We assign address of integer variable to void pointer | Void Pointer Becomes Integer Pointer |
When We assign address of character variable to void pointer | Void Pointer Becomes Character Pointer |
When We assign address of floating variable to void pointer | Void Pointer Becomes Floating Pointer |