C Language | Pointers | Generic Pointers

This article introduces void pointers, which can store pointers of any type. They are useful when passing pointers through functions without depending on a specific type.

Generic Types

Sometimes a function should receive a pointer without restricting its type. For example, a function may receive or return different pointer types depending on the situation.

Consider a function that initializes a memory range with a specified value regardless of type. Accepting char * would work, but callers with other pointer types would need casts.

The initialization operation does not depend on the data type. A generic pointer is appropriate. A void pointer can receive any pointer type and can be converted back with a cast.

Declaring a void Pointer

void * variableName

A void pointer can receive a pointer of any type. This makes it possible to write a simple function that receives pointers without depending on their types.

Code 1

#include <stdio.h>

void FillMemory(void *mem , int size , char n) {
 int iCount;
 for(iCount = 0 ; iCount < size ; iCount++)
    *((char *)mem + iCount) = n;
}

int main() {
 unsigned int iCount , iArray[8];
  FillMemory(iArray , 4 * 8 ,0xFF);

 for(iCount = 0 ; iCount < 8 ; iCount++)
   printf("iArray[%d] = %X\n" , iCount , iArray[iCount]);

 return 0;
}

FillMemory() receives a pointer to a memory region, its size, and an initialization value. The example creates an eight-element int array and initializes its 32 bytes to 0xFF, assuming four-byte integers.

Functions that receive raw memory addresses regardless of type are common. void pointers support abstractions required by extensible systems.