void pointer
- C course
- Intermediate
- Lesson 5/116
- 5 min
Learn to use generic pointers with void*.
void pointer (void*)
A void pointer (void *) is a generic pointer that holds an address of unknown type. Any data pointer can be implicitly converted to void *.
Example: int x = 5; void *p = &x;. Here p points to an int but the type is lost. To access the value through p you must first cast it to the right type: *(int *)p gives you 5. void * is the return type of malloc and the foundation of generic data structures such as tree nodes.
Generic functions with void*
With void * a single function can work with different types. The standard library's qsort is the best-known example: it takes a void * array and sorts it regardless of element type.
A generic print example: void print_int(void *p) { printf("%d\n", *(int *)p); }. This function takes an int * through a void * and prints it. The advantage is that you can write similar functions for different types with the same signature; the disadvantage is that type safety is lost at compile time.
Practice Print an int through void*
Write void print_int(void *p); inside it print *(int *)p with printf. In main declare int x = 99; and call print_int(&x).
Starter code
#include <stdio.h>
// Write print_int
// Declare an int in main and call it
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_int(void *p) {
printf("%d\n", *(int *)p);
}
int main(void) {
int x = 99;
print_int(&x);
return 0;
}Expected output
99
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you read an int through void *p?
- p->int
- *p
- p.int
- *(int *)p Correct answer
Explanation: Cast to (int *) first, then dereference with *.
2 Cast void* to int and print
int x = 7;
void *p = &x;
printf("%d\n", *(int *)____);
int x = 7;
void *p = &x;
printf("%d\n", *(int *)p);
Explanation: p is void*; first cast with (int *), then dereference with *.
3 Match the void* usage
| Term | Meaning |
|---|---|
void *p |
Generic pointer |
(int *)p |
Type cast |
*(int *)p |
Value access |
void *malloc(...) |
Allocation return |