8

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?

2
  • 6
    You'll generally get a better response if you post some code that you tried, even if it is not working, and explain as best you can exactly what the problem is. It demonstrates more effort on your part. Commented Mar 12, 2012 at 18:32
  • check this link Commented Mar 12, 2012 at 19:04

5 Answers 5

19
  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];
    
Sign up to request clarification or add additional context in comments.

1 Comment

Note: the link in the beginning is very helpful!
7

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);

Comments

5

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

Comments

2

Use typedefs

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.