diff options
author | Tom Ryder <tom@sanctum.geek.nz> | 2016-03-28 16:45:13 +1300 |
---|---|---|
committer | Tom Ryder <tom@sanctum.geek.nz> | 2016-03-28 16:45:13 +1300 |
commit | 764b6e2a3e8052ff2b4ce732963e6add97aa5291 (patch) | |
tree | a03f6793c8ec9cda541620e5bcaa23779e9c5ed5 | |
download | funcptr-764b6e2a3e8052ff2b4ce732963e6add97aa5291.tar.gz funcptr-764b6e2a3e8052ff2b4ce732963e6add97aa5291.zip |
Tinkering with function pointers
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | Makefile | 9 | ||||
-rw-r--r-- | funcptr.c | 43 |
3 files changed, 53 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d547342 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +funcptr diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..74fe256 --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +.PHONY: all clean + +CC = clang +CFLAGS = -std=c90 -Weverything + +all : funcptr + +clean : + rm -f funcptr diff --git a/funcptr.c b/funcptr.c new file mode 100644 index 0000000..de77066 --- /dev/null +++ b/funcptr.c @@ -0,0 +1,43 @@ +#include <stdio.h> +#include <stdlib.h> + +int doub(int); +int trip(int); +int half(int); +void fpv_exec(int (**fpv)(int), int n); + +int doub(int i) { + return i * 2; +} + +int trip(int i) { + return i * 3; +} + +int half(int i) { + return i / 2; +} + +void fpv_exec(int (**fpv)(int), int n) { + int i; + for (i = 0; *(fpv + i) != NULL; i++) { + printf("%d\n", (*(fpv + i))(n)); + } +} + +int main(int argc, char **argv) { + int (**fpv)(int); + fpv = calloc(4, sizeof(int (*)(int))); + + fpv[0] = doub; + fpv[1] = trip; + fpv[2] = half; + fpv[3] = NULL; + + for (argv++, argc--; argc; argv++, argc--) { + fpv_exec(fpv, atoi(*argv)); + } + + exit(EXIT_SUCCESS); +} + |