Use a hashing algorithm to parse numbers into function pointers:
This is also the simplest, without the hash of the address conflict, which can be described by the hash function as:
Func = Arr[index].func
Index is input, and the corresponding function pointer is returned according to the input index.
This architecture is simple, but it's very useful in testing.
For example, a test has dozens of items, I can use this architecture to implement automatic patrol test, or manually enter an index when interacting, that is, you can call the corresponding test function
In addition to this code, you can also learn the definition and use of function pointers:
Definition: typedef int (*FUNCPTR) (char *str);
Use:
Funcptr mainptr;
Char *str = "Test string!";
Mainptr = Hashfunc (1);
Mainptr (str);
The source code is as follows:
[Email protected]:/mnt/shared/appbox/hashfun# cat hashfun.c #include <stdio.h> #include <stdlib.h># Include <unistd.h> #include <string.h>typedef struct {int index; Int (*func) (char *str);} hashst;typedef Int (*funcptr) (char *str); int func0 (char *str); int func1 (char *str); Hashst hashstarr[] = {{0, func0}, {1, func1},};int func0 (char *str) {printf ("func1, str:%s!\n", str) ; return 0;} int func1 (char *str) {printf ("Func2, str:%s!\n", str); return 0;} /** Hash Function:func (index) = hashstarr[index].func*/funcptr hashfunc (int index) {return hashstarr[index].func;} int main (int argc, char *argv[]) {funcptr mainptr; Char *str = "Test string!"; Mainptr = Hashfunc (1); Mainptr (str); Mainptr = Hashfunc (1); Mainptr (str); return 0;} [Email protected]:/mnt/shared/appbox/hashfun#
The output is as follows:
[Email protected]:/mnt/shared/appbox/hashfun#/hashfun Func2, Str:test string!! Func2, Str:test string!!
The main function can be optimized to:
int main (int argc, char *argv[]) { funcptr mainptr; Char *str = "Test string!"; int i; for (i=0; i<2; i++) { mainptr = Hashfunc (i); Mainptr (str); } return 0;}
The input is also:
[Email protected]:/mnt/shared/appbox/hashfun#/hashfun func1, Str:test string!! Func2, Str:test string!!
Use a hashing algorithm to resolve numbers to function pointers-a schema method