What is a void pointer? 

A void pointer is a pointer that has no specific data type associated with it. Therefore, it can point to a variable of any data type. Void pointers are valid in C.

Declaring void pointers:

void *pointerName;
  • void indicates that the pointer is a void pointer
  • * indicates that the variable is a pointer variable
  • pointerName is the name of the pointer

Let us look at an example of declaring and initializing void pointer in C:

void *ptr;
char ch = ‘N’;
int num = 10;
ptr = &ch;
ptr = #

In the above code, we notice that since ptr is a void pointer, we can make it point to a variable of char type as well as a variable of int type. It can point to any type of variables.
Some important points to remember while using void pointers:

  • A void pointer cannot be dereferenced. We get a compilation error if we try to dereference a void pointer. This is because a void pointer has no data type associated with it. There is no way the compiler can know what type of data is pointed to by the void pointer. The solution is typecasting. To get the data pointed to by a void pointer we typecast it with the correct type of the data held inside the void pointers location.

Let us understand this with a code:

#include<stdio.h>
 
void main()
 
{
 
int num=10;//Intialising a normal varible
 
void *ptr;//Declaring a void pointer
 
ptr=#//Making ptr point to num
 
printf("The value of integer variable is= %d",*ptr );
 
}

When we run this code, we get a compilation error as follows:

exit status 1
main.c: In function 'main':
main.c:13:49: warning: dereferencing 'void *' pointer
printf("The value of integer variable is= %d",*ptr );
^~~~
main.c:13:49: error: invalid use of void expression

Look at us look at the same code. We use typecasting here to dereference the pointer:

#include<stdio.h>
 
void main()
 
{
 
int num=10;//Intialising a normal varible
 
void *ptr;//Declaring a void pointer
 
ptr=#//Making ptr point to num
 
printf("The value of integer variable is %d", *(int*)ptr );// Typecasting
 
}

The output will be:

The value of integer variable is 10

Therefore, by typecasting, we can dereference void pointers.

  • Pointer arithmetic is not allowed with a void pointer, it gives an error.

Uses of void pointers:

  • Void pointers are used in Generic functions in C.
  • malloc() and calloc() functions return void * type. This allows these functions to allocate memory to any data type.

[yuzo_views]












CopyRight © 2019

CopyRight © 2019