A void pointer is a pointer that is pointing to a type that is unknown. We cannot deference a void pointer because we don't know what it points to.
File: "void1.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//-------------------------------------------
void printArray( void* arr1 , int size, int sizeOfElement,
void (*printElement)(void*) )
{
for( int i1=0 ; i1<size ; i1++ )
{
printElement( (char*)arr1 + i1 * sizeOfElement ) ;
}
printf( "\n" ) ;
}
//-------------------------------------------
void printInt( void *element )
{
int* ptr1 = (int*) element ;
printf( "%d " , *ptr1 ) ;
}
//-------------------------------------------
void printDouble( void *element )
{
double* ptr1 = (double*) element ;
printf( "%.1lf " , *ptr1 ) ;
}
//-------------------------------------------
int main()
{
int arr1[5] = { 8, 4, 9, 1, 2 } ;
double arr2[5] = { 2.3 , 1.3 , 9.3 , 4.5 , 8.6 } ;
printArray( arr1, (sizeof(arr2)/sizeof(int)), sizeof(int), printInt ) ;
printArray( arr2, (sizeof(arr2)/sizeof(double)) ,
sizeof(double) , printDouble ) ;
return(0) ;
}
We can assign an int pointer to a void pointer but we can't deference it. So how do we use it ? Void pointers are usually used when we want to implement a generic kind feature in our programs.
The function "printArray" takes a pointer to a function and calls that to print the element. It uses void pointers so that we can specify different functions depending on our type. The function will take the void pointer and in this case figure out the next element using the expression: