Void Pointer in C

By | February 18, 2023

In C, a void pointer, also known as a generic pointer, is a pointer that can point to any type of data. The void type is a special type that represents the absence of any type. Therefore, a void pointer is a pointer that does not have any type associated with it.

Declaring Void Pointer in C::
Here is an example of how to declare a void pointer in C:

void *ptr;

In the above example, ptr is a void pointer that can point to any type of data.

However, when you use a void pointer, you cannot directly access the value it points to. Before you can access the value, you need to explicitly cast the void pointer to the correct type.

Using Void Pointer in C:
Here is an example of how to use a void pointer:

int i = 10;
float f = 3.14;
void *ptr;

ptr = &i;  // void pointer to the integer variable i
printf("%d\n", *(int *)ptr);  // Output: 10

ptr = &f;  // void pointer to the float variable f
printf("%f\n", *(float *)ptr);  // Output: 3.140000

In the above example, ptr is a void pointer that can point to any type of data. First, we set ptr to point to the integer variable i. To access the value of i using ptr, we first cast ptr to an integer pointer using (int *), and then we dereference it using the * operator. Similarly, we set ptr to point to the float variable f, and then we cast ptr to a float pointer to access its value.

Void pointers are commonly used in C to create generic functions that can operate on any type of data. They can also be used to implement polymorphism in C by creating a collection of void pointers that can point to different types of data.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.