Function pointers
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A function lies in memory too, and it has an address. A pointer to a function lets you pass behaviour around as a value:
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int (*op)(int, int); // op is a pointer to a function (int, int) → int
op = add;
printf("%d\n", op(2, 3)); // 5
op = mul;
printf("%d\n", op(2, 3)); // 6
The syntax is scary, so function pointers often get an alias with typedef:
typedef int (*binop)(int, int);
binop ops[] = {add, mul}; // a table of functions
The main example from the standard library is qsort. You give it a comparison function, and it sorts anything:
int cmp_int(const void *a, const void *b)
{
return *(const int *)a - *(const int *)b;
}
qsort(arr, n, sizeof(int), cmp_int);
This is how C does "polymorphism": event handlers, plugins, device drivers in the Linux kernel.
Task. Finish the function apply, which applies the given function to every item of an array. The program reads n, the array and an operation number (1 — double, 2 — square) and prints the result separated by spaces.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.