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

  1. Suppose we have to declare integer pointer,character pointer and float pointer then we need to declare 3 pointer variables.
  2. 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 :

  1. In C General Purpose Pointer is Called as void Pointer.
  2. It does not have any data type associated with it
  3. It can store address of any type of variable
  4. A void pointer is a C convention for a raw address.
  5. 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 :

ScenarioBehavior
When We assign address of integer variable to void pointerVoid Pointer Becomes Integer Pointer
When We assign address of character variable to void pointerVoid Pointer Becomes Character Pointer
When We assign address of floating variable to void pointerVoid Pointer Becomes Floating Pointer
In the next chapter we will study about dereferencing of void pointer variable.