What is a Void Pointer?

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.

--

--

--

Software-Hardware Geek | Blog https://stellasis.home.blog/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Writing OKRs in 1h or less

Support to assess physical, AWS, GCP servers now generally available

Stealing Keyboards and Other Leadership Techniques

How to Build and App to Manage Web App Translations

Flow applied to coding

Control Statements in JAVA

CS373 Spring 2021: Tejas Karuturi (Week 4)

JavaSonnet by Kanu Ratan Butani

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
Stella Sofia

Stella Sofia

Software-Hardware Geek | Blog https://stellasis.home.blog/

More from Medium

How C++ can learn from Ada: Distributed Systems

Embedded consulting tips: Dependency Injection (DI)

Programming Language:The new medium for everyone

From human to binary: A basic guide through the compilation process in C.