-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap2.c
More file actions
94 lines (62 loc) · 1.88 KB
/
Copy pathmap2.c
File metadata and controls
94 lines (62 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* map2.c */
/*
A simple program to map an integer (in a given range)
to a text string.
This code is released to the public domain.
"Share and enjoy...." ;)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
/* A function which returns a string according to the range
that an integer is in.
This function does the following mappings -
0..9 inclusive map to "foo"
10..19 inclusive map to "bar"
20..29 inclusive map to "baz"
Any other integer maps to "other". */
char *func(int inputval)
{
/* "Temp" is a helper function, to allow us to work around
C's non-support of ranges in the case statement. */
int temp = floor( (double) inputval / 10) ;
switch(temp)
{
case (0):
return "foo" ;
break;
case (1):
return "bar";
break;
case (2):
return "baz";
break;
default:
return "other" ;
}
}
/* Our map function to apply a function to an array. */
void map(int array[], int len, char *(*fn)(int) )
{
/* An array to store the results */
char *resarray[len] ;
int i;
for(i=0; i<len; i++)
{
resarray[i] = fn(array[i]);
printf("Array[%d] is %d, Result[%d] is %s\n", i, array[i], i, resarray[i]);
}
}
int main(void)
{
/* A function pointer to use */
char *(*ptr)(int) ;
/* Point the function pointer at our function */
ptr = func;
int myarray[] = { 3, 5, 11, 17, 24, 28, 37, 45};
int len = sizeof(myarray) / sizeof(*myarray);
map(myarray, len, *ptr);
return 0;
}