C void Pointer
In this page:
What is a void Pointer?
Because it carries no type information, the compiler can't perform any type-specific operations on it directly, but this also makes it the natural choice for functions like malloc() that need to hand back memory of any type.
Example: What is a void Pointer?
#include <stdio.h>
int main() {
void *ptr;
int x = 5;
ptr = &x;
printf("%d", *(int*)ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Assigning Addresses to void Pointers
This flexibility is exactly what makes void pointers useful for writing generic containers or functions (like qsort() or memcpy()) that need to work with data of any type without being rewritten for each one.
Example: Assigning Addresses to void Pointers
#include <stdio.h>
int main() {
int x = 5;
float f = 3.5f;
void *ptr;
ptr = &x;
ptr = &f;
printf("%.1f", *(float*)ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing a void Pointer
You must cast a void pointer back to a concrete type -- like int *p = (int*)voidPtr -- before you can dereference it, because the compiler needs to know how many bytes to read and how to interpret them.
Example: Dereferencing a void Pointer
#include <stdio.h>
int main() {
int x = 42;
void *voidPtr = &x;
int *p = (int*)voidPtr;
printf("%d", *p);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
void Pointers in Functions
This generality comes at the cost of type safety: the function has no way to verify at compile time that the caller passed the type of data it expects, so bugs here typically only surface at runtime.
Example: void Pointers in Functions
#include <stdio.h>
void printAsInt(void *data) {
printf("%d", *(int*)data);
}
int main() {
int x = 7;
printAsInt(&x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Pointer Arithmetic on void Pointers
This restriction exists because the compiler doesn't know the size of whatever void* is pointing to, so it has no way to calculate how far 'one element forward' actually is -- you must cast to a concrete pointer type first.
Example: Pointer Arithmetic on void Pointers
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
void *ptr = arr;
int *typedPtr = (int*)ptr;
typedPtr++;
printf("%d", *typedPtr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: