A function pointer in C is a pointer that stores the address of a function. It allows functions to be called indirectly and provides flexibility in program design, such as enabling callbacks, dynamic function calls, and implementing function tables.
Declaration:
C
return_type (*pointer_name)(parameter_list);
Example:
C
#include <stdio.h>
void greet() {
printf(“Hello, World!\n”);
}
int main() {
void (*func_ptr)(); // Declaring a function pointer
func_ptr = &greet; // Assigning the address of a function
func_ptr(); // Calling the function via the pointer
return 0;
}
Key Points:
1. Function Assignment: A function pointer can hold the address of any function with a matching signature.
2. Calling a Function: Use (*func_ptr)() or func_ptr() to call the function.
3. Applications: Used in callback mechanisms, dynamic dispatch, and creating jump tables for efficiency.
Function pointers provide powerful features but must be used carefully to avoid errors such as calling invalid memory locations.