What is a Void Pointer?

Stella Sofia
2 min readApr 24, 2020

--

Declaration of a void pointer in C

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.

--

--

Stella Sofia
Stella Sofia

Written by Stella Sofia

Tech explorer and life observer. Navigating the evolving landscape of software & sustainability.

No responses yet