Functions, Pointers, Structures Flashcards
What is a function pointer in C?
A variable that stores the address of a function, allowing functions to be passed around and called indirectly.
How do you declare a function pointer for a function that takes two int arguments and returns an int?
int (*f)(int, int);
How do you assign a function to a function pointer?
f = ∑ or f = sum; (both are valid)
How do you call a function using a function pointer?
f(a, b); or (*f)(a, b);
What are some uses of function pointers in C?
Passing functions as arguments
Implementing callbacks
Building lookup tables for function dispatch
Writing modular code (e.g., sorting with custom comparators)
How are function pointers used with qsort() in C?
You pass a comparator function that matches the signature expected by qsort, enabling custom sorting.
Can function pointers be members of a struct?
Yes, they can be used to define behavior in data structures, similar to methods in object-oriented programming.
Provide an example of a function pointer inside a struct.
typedef struct {
int (*operation)(int, int);
} Operator;
In the example operate(sum, a, b), what is sum?
A function passed as an argument to operate, which will call it using a function pointer.
What does this function pointer declaration mean: int (*f)(int, int);?
f is a pointer to a function that takes two int arguments and returns an int.
What is a function pointer table and how is it useful?
An array of function pointers used to select and call functions dynamically, often used in interpreters or state machines.
How can function pointers help emulate object-oriented behavior in C?
By combining data (structs) with function pointers (methods), we can mimic encapsulation and polymorphism.
What should you always ensure when using function pointers?
The function pointer must be initialized before use, and its signature must match the target function exactly.
What is a common pitfall with function pointers?
Mismatching function signatures or dereferencing an uninitialized/null pointer can cause undefined behavior.