How can I use an array of function pointers?

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

    You have a good example here (Array of Function pointers), with the syntax detailed.

    int sum(int a, int b);
    int subtract(int a, int b);
    int mul(int a, int b);
    int div(int a, int b);
    
    int (*p[4]) (int x, int y);
    
    int main(void)
    {
      int result;
      int i, j, op;
    
      p[0] = sum; /* address of sum() */
      p[1] = subtract; /* address of subtract() */
      p[2] = mul; /* address of mul() */
      p[3] = div; /* address of div() */
    [...]
    

    To call one of those function pointers:

    result = (*p[op]) (i, j); // op being the index of one of the four functions
    

提交回复
热议问题