A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type.
Advantages of void pointers:
1) malloc() and calloc() return void * type and this allows these functions to be used to allocate memory of any data type (just because of void *)
Note that the above program compiles in C, but doesn’t compile in C++. In C++, we must explicitly typecast return value of malloc to (int *).
2) void pointers in C are used to implement generic functions in C. For example compare function which is used in qsort().
Some Interesting Facts:
1) void pointers cannot be dereferenced. For example the following program doesn’t compile.
Compiler Error: 'void*' is not a pointer-to-object type
The following program compiles and runs fine.
2) The C standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it is allowed by considering the size of void is 1. For example the following program compiles and runs fine in gcc.
Note that the above program may not work in other compilers.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Double Pointer (Pointer to Pointer) in C
- Pointer to an Array | Array Pointer
- What is a Pointer to a Null pointer
- How does "void *" differ in C and C++?
- Difference between "int main()" and "int main(void)" in C/C++?
- Dangling, Void , Null and Wild Pointers
- Return from void functions in C++
- Is it fine to write "void main()" or "main()" in C/C++?
- How to declare a pointer to a function?
- Pointer vs Array in C
- 'this' pointer in C++
- Multidimensional Pointer Arithmetic in C/C++
- How to write C functions that modify head pointer of a Linked List?
- Function Pointer in C
- Opaque Pointer
- Passing by pointer Vs Passing by Reference in C++
- NULL pointer in C
- C | Pointer Basics | Question 1
- C | Pointer Basics | Question 2
- C | Pointer Basics | Question 3