How can I use an array of function pointers?

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

    This should be a short & simple copy & paste piece of code example of the above responses. Hopefully this helps.

    #include 
    using namespace std;
    
    #define DBG_PRINT(x) do { std::printf("Line:%-4d" "  %15s = %-10d\n", __LINE__, #x, x); } while(0);
    
    void F0(){ printf("Print F%d\n", 0); }
    void F1(){ printf("Print F%d\n", 1); }
    void F2(){ printf("Print F%d\n", 2); }
    void F3(){ printf("Print F%d\n", 3); }
    void F4(){ printf("Print F%d\n", 4); }
    void (*fArrVoid[N_FUNC])() = {F0, F1, F2, F3, F4};
    
    int Sum(int a, int b){ return(a+b); }
    int Sub(int a, int b){ return(a-b); }
    int Mul(int a, int b){ return(a*b); }
    int Div(int a, int b){ return(a/b); }
    int (*fArrArgs[4])(int a, int b) = {Sum, Sub, Mul, Div};
    
    int main(){
        for(int i = 0; i < 5; i++)  (*fArrVoid[i])();
        printf("\n");
    
        DBG_PRINT((*fArrArgs[0])(3,2))
        DBG_PRINT((*fArrArgs[1])(3,2))
        DBG_PRINT((*fArrArgs[2])(3,2))
        DBG_PRINT((*fArrArgs[3])(3,2))
    
        return(0);
    }
    

提交回复
热议问题