-4

all,I want to implement array_map function using c language . how can i do this?

void * x_array_map(void * func, Array * arr){
   //TODO
}

Thx!

Tobi
  • 31
  • 3

1 Answers1

0

Here is some reference about function as parameter,

How do you pass a function as a parameter in C?

Here is my code:

#include <stdio.h>
#include <stdlib.h>

#define param_type int

// prototype
param_type* array_map (param_type (*f)(param_type), param_type* arr, int n);

// dummy function
int cube(int x) {
    return x*x*x;
}

int main (){
    int a[3] = {1, 2, 3};
    int* b = array_map(cube, a, 3);
    for (int i = 0; i < 3; ++i) {
        printf("%d\n", b[i]);
    }
    return 0;
}

param_type* array_map (param_type (*f)(param_type), param_type* arr, int n) {
    param_type* result = (param_type*) malloc(n*sizeof(param_type));
    for (int i = 0; i < n; ++i)
        result[i] = f(arr[i]);
    return result;
}
Community
  • 1
  • 1
ibrohimislam
  • 717
  • 7
  • 21