How can I use an array of function pointers?

前端 未结 10 1134
别那么骄傲
别那么骄傲 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:52

    Can use it in the way like this:

    //! Define:
    #define F_NUM 3
    int (*pFunctions[F_NUM])(void * arg);
    
    //! Initialise:
    int someFunction(void * arg) {
        int a= *((int*)arg);
        return a*a;
    }
    
    pFunctions[0]= someFunction;
    
    //! Use:
    int someMethod(int idx, void * arg, int * result) {
        int done= 0;
        if (idx < F_NUM && pFunctions[idx] != NULL) {
            *result= pFunctions[idx](arg);
            done= 1;
        }
        return done;
    }
    
    int x= 2;
    int z= 0;
    someMethod(0, (void*)&x, &z);
    assert(z == 4);
    

提交回复
热议问题