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
| [root@localhost source]# cat main.c #include "stdio.h" #include "string.h"
int append(char *buff, int index, const char *str) { int len = strlen(str); memcpy(buff + index, str, len); return len; }
int append_first(char *buff, int index, const char *str) { return append(buff, index, str); }
int append_more(char *buff, int index, const char *str) { index += append(buff, index, ","); index += append(buff, index, str); return index; }
//void show_code(const char **str, int (*func[])(char *buff, int index, const char *str)) //等效 void show_code(const char **str, int (*(*func))(char *buff, int index, const char *str)) { char buff[1024]; int index = 0;
for(int i = 0; str[i]; i++) { int select = !!i; index += func[select](buff, index, str[i]); } buff[index] = '\0';
printf("[%s]\n", buff); }
int main() { int (*func[])(char *buff, int index, const char *str) = { append_first, append_more, NULL, };
const char *str1[]={"Hello", NULL,}; const char *str2[]={"Hello", "World", NULL,};
show_code(str1, func); show_code(str2, func);
return 0; } [root@localhost source]#
|