Module 6 · Pointers and Memory — topic 3 of 5
Pointers and Functions
Passing pointers lets functions modify the caller's data and return multiple results; returning pointers needs care with lifetimes; function pointers let you pass behaviour as data, as qsort does.
Learning objectives
- Write functions that modify arguments through pointers
- Return pointers safely
- Declare and use function pointers, including with qsort
Definition
A pointer parameter receives a copy of an address, through which the function can access the caller's object (simulated pass-by-reference). A function pointer is a pointer whose type includes the function's parameter and return types, and through which the function can be called.
Introduction
Because C passes arguments by value, a function can't change the caller's variables directly. Pass their addresses instead, and the function can write through them. This is how scanf fills your variables and how a swap function works.
Functions themselves have addresses too. A function pointer lets you hand a function to another function — a callback. The standard qsort uses this to sort any type with a comparison function you supply.
Why it matters
Output parameters, swapping, in-place updates and returning several results all rely on pointer parameters.
Function pointers enable plug-in behaviour: sorting orders, event handlers, menu dispatch tables and state machines.
Detailed explanation
A parameter int *out receives an address; *out = value; stores into the caller's variable. The caller passes &variable.
Use const to document intent: void print(const int *a, int n) promises not to modify the array. const int *p is a pointer to const data; int *const p is a constant pointer to mutable data.
Returning a pointer is safe only if the object outlives the call: a static object, a heap allocation, or memory owned by the caller. Never return the address of a local (automatic) variable.
A function pointer declaration names the signature: int (*cmp)(const void *, const void *); — the parentheses around *cmp are required. Assign with cmp = compare_ints; and call with cmp(a, b).
qsort(base, count, size, cmp) sorts any array. cmp receives const void * pointers to two elements and returns negative, zero or positive.
Syntax
- Pass
&xfor anint *parameter. - Without parentheses,
int *f(int)declares a function returningint *. - A
typedefmakes function pointer types readable:typedef int (*BinOp)(int, int);.
Code examples
Swap through pointers
x=2 y=1
Returning two results
min=3 max=88
More examples
Function pointers and qsort
add(6, 3) = 9 sub(6, 3) = 3 mul(6, 3) = 18 5 5 17 23 40 C C++ Java Python
Step-by-step explanation
typedef int (*BinOp)(int, int);names the type “pointer to a function taking two ints and returning int”.tableis an array of function pointers — a dispatch table;table[i](6, 3)calls the i-th function.ascconverts itsconst void *arguments back toconst int *and returns −1, 0 or 1 without risking overflow (unlikex - y).- For an array of strings, each element is a
const char *, so the comparator receives pointers to those pointers. qsortworks on both arrays because it only needs the element size and the comparator.
Expected output
Running “Function pointers and qsort” prints exactly:
Practical applications
- GUI toolkits register callbacks for button clicks.
- Operating systems use tables of function pointers for device drivers.
qsortandbsearchfrom<stdlib.h>work on any data via comparators.
Best practices
- Mark input-only pointer parameters
const. - Document who owns memory a returned pointer refers to.
- Use
typedeffor function pointer types.
Common mistakes
Passing a value where an address is needed
Avoid
Prefer
swap expects int *. Passing ints makes it treat 1 and 2 as addresses — a crash. The compiler warns.
Comparator that can overflow
Avoid
Prefer
Subtracting large ints of opposite sign overflows (undefined behaviour) and gives the wrong order.
Important notes
- A function name used as a value decays to a function pointer, so
&addandaddare equivalent. - Converting between function pointers and
void *is not portable in ISO C, though POSIX systems allow it.
Key takeaways
- Pass addresses to let functions modify caller variables.
- Return pointers only to objects that outlive the function.
- Function pointers enable callbacks such as qsort comparators.
Try it yourself
- 1Write
void stats(const double *a, int n, double *mean, double *stddev). - 2Sort an array of student structs by marks (descending) using qsort.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhy must `scanf` receive `&x` rather than `x`?
- ModerateWhat is wrong with this function? `int *make(void) { int v = 42; return &v; }`