ProgrammingSystem Programmer

Explain the features of declaring and using function pointers in C. How to correctly store an array of pointers to different functions and call them dynamically?

Pass interviews with Hintsage AI assistant

Answer

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
  • This approach allows for creating command tables, handlers, or automatically linking actions to operation numbers.
  • All functions must have the same signature.
  • When working with function pointers, the types must match exactly.

Trick Question

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

Examples of real errors due to ignorance of the topic's nuances


Story

In a plugin system project, a table of function pointers with different signatures was placed (one returned int, the other void). When running on some architectures, stack corruption occurred.

Story

In an old command management system, an array of function pointers was used. A newcomer added a function with additional parameters, leading to unpredictable behavior after transitioning to the new element of the array.

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.