Summary - Advanced pointers
- C course
- Intermediate
- Lesson 6/116
- 5 min
Combine double pointer, function pointer and void* to write a sorting app.
Bringing advanced pointers together
In this group you learned four concepts: double pointer (**), array of pointers, function pointer and void *. Now we'll combine them in a sorting application.
The sort function takes an array of int * as int **. It compares through a function pointer int (*cmp)(int, int). We pass the pointer array through a void * generic pointer; this mimics the flexibility of real library APIs. So one sort function can work with different comparisons.
Practice Sort an array of pointers
Write int greater(int a, int b) returning a > b. Define void sort_ptrs(int **items, int n, int (*cmp)(int, int)); do bubble sort, swapping neighbor pointers with an int * tmp when cmp is true. In main declare int v[3] = {5, 2, 8}; and int *ptrs[3] = {&v[0], &v[1], &v[2]};. Write void *generic = ptrs; and int **items = (int **)generic;. Call sort_ptrs(items, 3, greater), then print *items[i] in a for loop with printf.
Starter code
#include <stdio.h>
// Write greater
// Write sort_ptrs
// Sort and print in main
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int greater(int a, int b) { return a > b; }
void sort_ptrs(int **items, int n, int (*cmp)(int, int)) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (cmp(*items[j], *items[j + 1])) {
int *tmp = items[j];
items[j] = items[j + 1];
items[j + 1] = tmp;
}
}
}
}
int main(void) {
int v[3] = {5, 2, 8};
int *ptrs[3] = {&v[0], &v[1], &v[2]};
void *generic = ptrs;
int **items = (int **)generic;
sort_ptrs(items, 3, greater);
for (int i = 0; i < 3; i++) printf("%d ", *items[i]);
printf("\n");
return 0;
}Expected output
2 5 8
Summary
In this group you learned advanced pointer concepts. A double pointer holds a pointer's address; an array of pointers is common for string lists; a function pointer selects behavior at runtime; a void * is a generic pointer with lost type that requires an explicit cast.
You combined them to write a flexible sorting application. In the next groups these concepts return in memory management and dynamic data structures. qsort and callback patterns in particular build on these foundations.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the concepts with their uses
| Term | Meaning |
|---|---|
int **items |
Double pointer |
int (*cmp)(int, int) |
Function pointer |
void *generic |
Generic pointer |
int *ptrs[3] |
Pointer array |
2 What does void* do in the sort function?
- Is used in the loop
- Carries the pointer array generically Correct answer
- Does the comparison
- Prints values
Explanation: Void* carries the pointer array generically, then is cast to int**.