In Lesson 13 of Learn C With Me, we continue Chapter 11 — Pointers II from Beej’s Guide to C Programming, this time exploring one of C’s most interesting features: void pointers.
We learn how a pointer can refer to data without specifying its type, why generic pointers are useful, and how standard library functions such as memcpy() and qsort() can work with different kinds of data.
We cover:
- What
void *means in C - The difference between typed pointers and generic pointers
- Why
void *can point to different data types - Understanding generic functions
- Using
memcpy()to copy memory - Source and destination pointers
- Understanding byte counts and
size_t - Copying character arrays and other data
- Why
void *cannot be dereferenced directly - Why standard C doesn’t support arithmetic on
void * - Converting generic pointers to typed pointers
- Using casts when working with pointers
- Understanding pointer types and memory representation
- Returning pointers from functions
- Why library functions often return
void * - Introducing
qsort() - Sorting arrays containing structs
- Writing a comparison function
- Why comparison functions receive
const void *arguments - Converting those arguments to the appropriate pointer type
- Sorting structs by one of their fields
- Understanding the arguments passed to
qsort() - How comparison results determine sorting order
- Compiler errors, debugging and reading manual pages
One of the biggest challenges in this lesson is understanding how void * makes generic programming possible in C. A function such as memcpy() doesn’t need to know whether it is copying characters, integers or other data. It works with memory and a specified number of bytes.
We also discover the limitations of generic pointers. Since a void * doesn’t specify the pointed-to object’s type, we cannot simply dereference it or perform ordinary pointer arithmetic on it.
Later, we experiment with qsort(), sorting an array of animal structs by their number of legs. This introduces another important concept: passing a comparison function to a library function so it knows how to order our data.
As usual, we read the book, experiment, make mistakes, consult the manual pages, get help from the live chat, and try to understand why C works the way it does.
This stream completes our exploration of Pointers II.
