Function pointer array
- C course
- Intermediate
- Lesson 28/116
- 5 min
Learn dispatch tables with function pointer arrays.
Function pointer array
A function pointer array is an array whose elements are function pointers. This structure forms a dispatch table; it selects the function to call based on an index.
Example: int (*ops[2])(int, int) = {add, sub};. This is a two-element function pointer array. Calling ops[0](5, 3) invokes add(5, 3); ops[1](10, 4) invokes sub(10, 4). This pattern replaces a switch-case chain; it makes the code cleaner and more extensible. To add a new operation you just append an element to the array.
The dispatch table advantage
The dispatch table is cleaner than a switch-case chain. To add a new operation you just append to the array; the calling logic stays the same.
Example: in a calculator, instead of switch (op) { case 0: add(a,b); ... } you write ops[op](a, b). To add a 'mul' operation you append mul to the ops array; the call becomes ops[2](a, b). Unlike switch-case, the dispatch table separates data from behavior; this makes extension easy. This pattern is standard in command-line apps and interpreters.
Practice Write a calculator
Write int add(int a, int b) and int sub(int a, int b). Declare a function pointer array with int (*ops[2])(int, int) = {add, sub};. Call both operations: printf("%d\n", ops[0](5, 3)); and printf("%d\n", ops[1](10, 4));.
Starter code
#include <stdio.h>
// Write add and sub
// Declare ops function pointer array
// Call both operations in main
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main(void) {
int (*ops[2])(int, int) = {add, sub};
printf("%d\n", ops[0](5, 3));
printf("%d\n", ops[1](10, 4));
return 0;
}Expected output
8 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match operation to function
| Term | Meaning |
|---|---|
ops[0] |
add function |
ops[1] |
sub function |
{add, sub} |
Initializer list |
int (*ops[2])(...) |
Array type |
2 Complete the dispatch call
int (*ops[2])(int, int) = {add, sub};
int r = ____[0](5, 3);
int (*ops[2])(int, int) = {add, sub};
int r = ops[0](5, 3);
Explanation: ops[0](5, 3) calls the add function.
3 What does a dispatch table do?
- Allocates memory
- Calls a function by index Correct answer
- Reads a file
- Copies a string
Explanation: A dispatch table selects the function to call by index.