Question 3
Back to Exercise
Write map() that applies any int → int function to each element, using a typedef for the callback type.
Solution
#include <stdio.h>
typedef int (*Mapper)(int);
void map(int *a, size_t n, Mapper f) {
for (size_t i = 0; i < n; i++)
a[i] = f(a[i]);
}
void print(const int *a, size_t n) {
for (size_t i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
static int square(int x) { return x * x; }
static int negate(int x) { return -x; }
int main(void) {
int a[] = {1, 2, 3, 4};
map(a, 4, square);
print(a, 4);
map(a, 4, negate);
print(a, 4);
return 0;
}
1 4 9 16 -1 -4 -9 -16
The loop is written once; the behaviour is a parameter. The Mapper typedef keeps the signature of map() readable.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!