De-Referencing Void Pointers in C Programming Language

January 7, 2012 No Comments » Hits : 198





Prerequisite : De-Referencing a pointer

How to de-reference a pointer ?
Void Pointers are -

  • General Purpose
  • Stores the address of any type of variable
  • Check this article to know more about void pointer.

Why it is necessary to use Void Pointer ?


Reason 1 : Re-usability of Pointer 

float *ptr;
int num;

ptr = &num ;  // Illegal Use of Pointer

So in order to increase the re-usability of the Pointer it is declared as void Pointer.


De-Referencing void Pointer :
Consider this example -

void *ptr;    // ptr is declared as Void pointer

char cnum;
int inum;
float fnum;

Suppose we have assigned integer Address to void pointer then -

ptr = &inum;  // ptr has address of integer data

then to De-reference this void pointer we should use following syntax -

*((int*)ptr)

Similarly we should use following for Character and float -

*((float*)ptr)  // De-reference Float Value
*((char*)ptr)   // De-reference Character Value

Following table will summarize all details -

Whose Address is stored in Void Pointer ?How to De-Reference it ?
Integer*((int*)ptr)
Charcter*((char*)ptr)
Floating*((float*)ptr)

Live Example :

#include<stdio.h>

int main()
{
int inum = 8;
float fnum = 67.7;
void *ptr;

// Assign address of Integer to void pointer
ptr = &inum;
printf("\nThe value of inum = %d",*((int*)ptr));

// Assign address of Float to void pointer
ptr = &fnum;
printf("\nThe value of fnum = %f",*((float*)ptr));

return(0);
}

Output :

The value of inum = 8
The value of fnum = 67.7

Incoming search terms: