← Back to C Course | Chapter 7: Pointers | Lesson 8 of 9

C void Pointer

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?

c
#include <stdio.h>
int main() {
	void *ptr;
	int x = 5;
	ptr = &x;
	printf("%d", *(int*)ptr);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int x = 5;
	float f = 3.5f;
	void *ptr;
	ptr = &x;
	ptr = &f;
	printf("%.1f", *(float*)ptr);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int x = 42;
	void *voidPtr = &x;
	int *p = (int*)voidPtr;
	printf("%d", *p);
	return 0;
}

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

c
#include <stdio.h>
void printAsInt(void *data) {
	printf("%d", *(int*)data);
}
int main() {
	int x = 7;
	printAsInt(&x);
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.