Created
December 11, 2012 23:30
-
-
Save dafrancis/4263337 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int square(int x){ | |
return x * x; | |
} | |
int *map(int array[], int size, int (*f)(int)){ | |
int i; | |
int *out = calloc(size, sizeof(int)); | |
for(i=0; i<size; i++){ | |
// In this example I'm using map to give back an array of | |
// the values squared. therefore you could view (f)(array[i]) | |
// as (squared)(array[i]) or squared(array[i]) | |
out[i] = (f)(array[i]); | |
} | |
return out; | |
} | |
int main() { | |
int array[3] = {1, 2, 3}; | |
int array_size = sizeof(array)/sizeof(int); | |
int *mapped_array = map(array, array_size, square); | |
int i; | |
for(i=0; i<array_size; i++){ | |
printf("%d = %d\n", i, mapped_array[i]); | |
} | |
// Because I've allocated some memory for the mapped array I must free it. | |
free(mapped_array); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment