LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 3

Apply a typedef'd callback to every array element in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write map() that applies any int → int function to each element, using a typedef for the callback type.

Solution
main.c
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links