How to Create Array of Function Pointers in C: Syntax and Example
In C, you create an array of function pointers by declaring an array where each element is a pointer to a function with a specific signature, for example,
int (*arr[])(int) declares an array of pointers to functions taking an int and returning an int. You can assign functions to this array and call them using the pointers like arr[0](5).Syntax
To declare an array of function pointers, you specify the return type and parameter types of the functions, then use parentheses and asterisk to indicate pointers, followed by the array name and size.
- Return type: The type the functions return (e.g.,
int). - Pointer syntax:
(*arr[])means an array of pointers. - Parameter list: The types of parameters the functions accept (e.g.,
(int)).
c
int (*arr[])(int);
Example
This example shows how to declare an array of function pointers, assign functions to it, and call them through the array.
c
#include <stdio.h> // Functions matching the signature: take int, return int int square(int x) { return x * x; } int cube(int x) { return x * x * x; } int increment(int x) { return x + 1; } int main() { // Declare array of 3 function pointers int (*funcs[3])(int) = {square, cube, increment}; int value = 4; for (int i = 0; i < 3; i++) { printf("Result of function %d: %d\n", i, funcs[i](value)); } return 0; }
Output
Result of function 0: 16
Result of function 1: 64
Result of function 2: 5
Common Pitfalls
Common mistakes when working with arrays of function pointers include:
- Forgetting parentheses around the pointer declaration, which changes the meaning.
- Mismatching function signatures between the pointer type and assigned functions.
- Calling functions without using the pointer syntax correctly.
Here is an example of a wrong declaration and the correct way:
c
// Wrong: missing parentheses, declares array of functions, not pointers int funcs_wrong[3](int); // This is invalid syntax // Correct declaration int (*funcs_correct[3])(int);
Quick Reference
Remember these tips when using arrays of function pointers:
- Use parentheses around
*arrayName[]to declare an array of pointers. - Ensure all functions assigned have the same signature.
- Call functions via pointers using
arrayName[index](arguments).
Key Takeaways
Declare arrays of function pointers with parentheses: int (*arr[])(int).
Assign functions with matching signatures to the array elements.
Call functions using the pointer syntax: arr[index](argument).
Always match the function pointer type exactly to avoid errors.
Parentheses placement is crucial to distinguish pointers from arrays of functions.