Array of function pointers in C

2020-06-16 02:40发布

问题:

I'm having really hard time comprehending the syntax for function pointers. What I am trying to do is, have an array of function pointers, that takes no arguments, and returns a void pointer. Can anyone help with that?

回答1:

  1. First off, you should learn about cdecl:

    cdecl> declare a as array 10 of pointer to function(void) returning pointer to void
    void *(*a[10])(void )
    
  2. You can do it by hand - just build it up from the inside:

    a

    is an array:

    a[10]

    of pointers:

    *a[10]

    to functions:

    (*a[10])

    taking no arguments:

    (*a[10])(void)

    returning void *:

    void *(*a[10])(void)

  3. It's much better if you use typedef to make your life easier:

    typedef void *(*func)(void);
    

    And then make your array:

    func a[10];
    


回答2:

Whenever compound syntax gets too complicated, a typedef usually clears things up.

E.g.

typedef void *(* funcPtr)(void);

funcPtr array[100];

Which without the typedef I guess would look like:

void *(* array[100])(void);


回答3:

Start with the array name and work your way out, remembering that [] and () bind before * (*a[] is an array of pointer, (*a)[] is a pointer to an array, *f() is a function returning a pointer, (*f)() is a pointer to a function):

        farr               -- farr
        farr[N]            -- is an N-element array
       *farr[N]            -- of pointers
      (*farr[N])(    )     -- to functions
      (*farr[N])(void)     --   taking no arguments
     *(*farr[N])(void)     --   and returning pointers
void *(*farr[N])(void);    --   to void


回答4:

Use typedefs

typedef void* func(void);
func *arr[37];


回答5:

Check out http://www.newty.de/fpt/fpt.html#arrays for examples and explainations of arrays of C and C++ function pointers.