How can I use an array of function pointers?

前端 未结 10 1217
别那么骄傲
别那么骄傲 2020-11-22 17:24

How should I use array of function pointers in C?

How can I initialize them?

10条回答
  •  余生分开走
    2020-11-22 17:36

    This question has been already answered with very good examples. The only example that might be missing is one where the functions return pointers. I wrote another example with this, and added lots of comments, in case someone finds it helpful:

    #include 
    
    char * func1(char *a) {
        *a = 'b';
        return a;
    }
    
    char * func2(char *a) {
        *a = 'c';
        return a;
    }
    
    int main() {
        char a = 'a';
        /* declare array of function pointers
         * the function pointer types are char * name(char *)
         * A pointer to this type of function would be just
         * put * before name, and parenthesis around *name:
         *   char * (*name)(char *)
         * An array of these pointers is the same with [x]
         */
        char * (*functions[2])(char *) = {func1, func2};
        printf("%c, ", a);
        /* the functions return a pointer, so I need to deference pointer
         * Thats why the * in front of the parenthesis (in case it confused you)
         */
        printf("%c, ", *(*functions[0])(&a)); 
        printf("%c\n", *(*functions[1])(&a));
    
        a = 'a';
        /* creating 'name' for a function pointer type
         * funcp is equivalent to type char *(*funcname)(char *)
         */
        typedef char *(*funcp)(char *);
        /* Now the declaration of the array of function pointers
         * becomes easier
         */
        funcp functions2[2] = {func1, func2};
    
        printf("%c, ", a);
        printf("%c, ", *(*functions2[0])(&a));
        printf("%c\n", *(*functions2[1])(&a));
    
        return 0;
    }
    

提交回复
热议问题