Introduction and usage analysis of void pointers in C/C++

A null pointer is a pointer that doesn’t have any associated data types. A null pointer can hold any type of address and can convert its type to any type.

int a = 10;
char b = 'x' ;
void *p = &a;  //void pointer holds address of int 'a'
p = &b; //void pointer holds address of char 'b'

Advantages of void pointers:

  1. malloc() and calloc() return the void * type, which allows these functions to be used to allocate memory for any data type (only due to void *)
int main(void)
{
     //Note that malloc() returns void * which can be 
     //typecasted to any type like int *, char *, ..
     int *x = malloc(sizeof(int) * n);
}

Please note that the above programs are compiled in C, but not in C++. In C++, we have to explicitly convert the return value of malloc to (int*).

2. The void pointer in C is used to implement generic functions in C. For example, the comparison function used in qsort().

Some interesting facts:

  1. Invalid pointers cannot be dereferenced. For example, the following programs fail to compile.
#include<stdio.h>
int main()
{
     int a = 10;
     void *ptr = &a;
     printf ( "%d" , *ptr);
     return 0;
}

The output is as follows:

Compiler Error: 'void*' is not a pointer-to-object type

The following programs compile and run normally.

#include<stdio.h>
int main()
{
     int a = 10;
     void *ptr = &a;
     printf ( "%d" , *( int *)ptr);
     return 0;
}

The output is as follows:

10

2. The C criterion does not allow pointer arithmetic using invalid pointers. However, in GNU C, it is permissible to consider void as a size of 1. For example, the following program compiles and works well in GCC.

#include<stdio.h>
int main()
{
     int a[2] = {1, 2};
     void *ptr = &a;
     ptr = ptr + sizeof ( int );
     printf ( "%d" , *( int *)ptr);
     return 0;
}

The output is as follows:

2

Please note that the above programs may not run in other compilers.

If you find anything incorrect, or if you would like to share more information about the above topics, please leave a comment