Array of function pointers in C
Asked Answered
D

5

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?

Dendro answered 12/3, 2012 at 18:30 Comment(2)
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.Hortenciahortensa
check this linkPunishable
A
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];
    
Arachnid answered 12/3, 2012 at 18:33 Comment(1)
Note: the link in the beginning is very helpful!Checkoff
N
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);
Nitrification answered 12/3, 2012 at 18:34 Comment(0)
E
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
Emie answered 12/3, 2012 at 18:58 Comment(0)
I
2

Use typedefs

typedef void* func(void);
func *arr[37];
Ingredient answered 12/3, 2012 at 18:33 Comment(0)
H
0

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

Homestretch answered 12/3, 2012 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.