C dereferencing void pointer



In the last chapter we have learnt about void pointer. In this chapter we will be learning Dereferencing Void Pointer in C Programming.

Must Read Article : Dereferencing the Pointer Variable

[box]Void Pointer is called as General Purpose Pointer.[/box]

Why it is necessary to use Void Pointer ?

Reason 1 : Re-usability of Pointer 

float *ptr;
int num;

ptr = &num ;  // Illegal Use of Pointer

In the above example we have declared float pointer which is of no use in the program. We cannot use float pointer to store the integer pointer so So in order to increase the re-usability of the Pointer it is necessary to declared pointer variable as void Pointer.

Dereferencing 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 –

Type of Address Stored in Void Pointer Dereferencing Void Pointer
Integer *((int*)ptr)
Charcter *((char*)ptr)
Floating *((float*)ptr)

Live Example : Dereferencing Void Pointer

#include<stdio.h>

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

ptr = &inum;  
printf("\nThe value of inum = %d",*((int*)ptr));

ptr = &fnum;  
printf("\nThe value of fnum = %f",*((float*)ptr));

return(0);
}

Output :

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

Explanation : Void Pointer Program

ptr = &inum;  
printf("\nThe value of inum = %d",*((int*)ptr));

Here we are assigning the address of integer variable to void pointer so that void pointer can act as Integer pointer.

ptr = &fnum;  
printf("\nThe value of fnum = %f",*((float*)ptr));

And now we are storing the address of floating point variable to void pointer , thus void pointer becomes floating pointer.

In the next chapter we will be learning the Different Operations on Pointer Variable such as Incrementing Pointer and Decrementing Pointer.