Skip to main content

Void Pointer in C

Void Pointer

The void pointer is declared as void * and can be used to pass pointers to functions that do not need to know the data type they are handling.

It is also known as a "generic pointer", and can hold the address of any type of data, but it does not know the type of the data it is pointing to. However, before dereferencing a void pointer, it must be cast to the correct data type.

Void Pointer - Examples

Example 1

#include <stdio.h>

int main()
{
int num = 10;
char c = 'a';
void *ptr;

// Assign the address of an int to the void pointer
ptr = &num;

// Cast the void pointer to an int pointer and dereference it
printf("The value of num is %d\n", *(int *)ptr);

// Assign the address of a char to the void pointer
ptr = &c;

// Cast the void pointer to a char pointer and dereference it
printf("The value of c is %c\n", *(char *)ptr);

return 0;
}
Output:

Explanation

  • A void pointer is used to store the address of an integer and a character.

  • The void pointer is then cast to the appropriate pointer type (int* and char*) before dereferencing it to obtain the value of the data being pointed to.

Example 2

#include <stdio.h>

void print_value(void *ptr, char type)
{
switch (type)
{
case 'i':
printf("%d\n", *(int *)ptr);
break;
case 'f':
printf("%f\n", *(float *)ptr);
break;
case 'c':
printf("%c\n", *(char *)ptr);
break;
default:
printf("Invalid type\n");
break;
}
}

int main()
{
int i = 10;
float f = 3.14;
char c = 'a';

// Call the print function with different types of data
print_value(&i, 'i');
print_value(&f, 'f');
print_value(&c, 'c');

return 0;
}
Output:

Example

  • The print_value() function takes a void pointer and a character representing the type of data being pointed to.
  • The function uses a switch statement to cast the void pointer to the appropriate type (int*, float*, or char*) and then prints the value of the data being pointed to.
  • The main function calls the print_value() function with different types of data to demonstrate its ability to print values of different types using a single function.