A function pointer in C is a variable that holds the address of a function, allowing for the dynamic selection of which function to call. The typical declaration of a function pointer is:
// Function pointer taking an int and returning an int int (*f_ptr)(int);
For an array of pointers:
int func1(int x) { return x + 1; } int func2(int x) { return x * 2; } int (*f_arr[2])(int) = { func1, func2 }; int result = f_arr[1](10); // will return 20
Can a function with a different signature be called using a function pointer?
Common incorrect answer: "Yes, if type casting is used."
Correct answer: Technically, this is possible due to the dynamic nature of pointers, but this action leads to runtime bugs and unpredictable behavior, as functions with different calling conventions and argument arrangements are invoked.
Example:
void funcA(int x) { printf("A: %d ", x); } void funcB(float y) { printf("B: %f ", y); } void (*fptr)(int) = (void (*)(int)) funcB; fptr(5); // ERROR: incorrect data will be passed
Story
Story
Story
In the firmware, the result of changing function pointers was not checked. Insufficient initialization of the handler array led to a null pointer (NULL) being called, causing the device to hang without notifying the user.