What is a Void Pointer?

A void pointer in C is a convertible pointer that points to variables of any data type and therefore it cannot be simply dereferenced. With this, you might ask, in what circumstances you can use it?

Good question.

Well, it is primarily used when you need to point to different types of data at different times in your program. You can then obtain the value by casting to that specific kind of pointer.

So let’s say you need to track an integer a and a character b. You can avoid using 2 pointers, that is, int pointer and char pointer, and use only a void pointer. The program looks like this:

//CODE:
#include <stdio.h>

int main() {
void *ptr;

int a = 1;
ptr = &a;
int aValue = *(int*)ptr; // casting is performed here
printf("ptr int value through casting = %d\n", aValue);

char b = 'b';
ptr = &b;
char bValue = *(char*)ptr; // another casting
printf("ptr char value through casting = %c\n", bValue);
}

//OUTPUT:
//ptr int value through casting = 1
//ptr char value through casting = b

Now what can we conclude? Well, the void pointer is a general-purpose pointer. Point it to any data type, keep track of it (at least in your head) and you’re good to go. Pretty cool right? Not quite. This isn’t considered a good practice because it poses type checking problems. For this reason, it’s always recommended not to use it unless it’s absolutely necessary.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store