0

Possible Duplicate:
how to use array of function pointers?

I am wondering how one can declare in C a dynamic list of function pointers ? Using a pointer to function pointer ?

Community
  • 1
  • 1
Manuel Selva
  • 18,554
  • 22
  • 89
  • 134
  • Note that http://cdecl.org/ is really useful for these things: searching "array 5 of pointer to function (int, float, double) returning int" gives you an example of a static list. – huon Aug 02 '12 at 14:53

3 Answers3

2

A pointer to a function pointer, with which you can use to point to a block of dynamically allocated memory. Let's say the function type is void (int):

void (*(*))(int) // Bare type
void (*(*f))(int) // Variable

Or you may want an array to function pointers, in which case:

void (*[10])(int) // Bare type
void (*af[10])(int) // Variable

You can change the parameter and the return type of the functions.

An array of function pointers can be used as a map from number to function to be executed. It is one way to do emulation - for example, after you have obtained the OP code from the instruction, you can execute the operation by using the array of pointer. (This is one way to do so, but I'm not sure whether it is actually done in emulation code).

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
1

Yes you can have an array of function pointers.

This might be useful, for instance for collecting a set of callback functions for a specific event.

As an example, consider implementing addEventListener to DOM elements in a browser, where any DOM element can have multiple click events. A simple data structure might be:

void (*clickHandlers[MAX_EVENT_HANDLERS])(EventData arg);

For a dynamic list then allocate a buffer of function pointers using malloc, and realloc as you need more space:

void (**clickHandlers)(EventData arg);
pb2q
  • 58,613
  • 19
  • 146
  • 147
1

For a dynamic list, you can use a basic linked list:

struct list {
   int (*func)(int, float, double);
   struct list *next;
}

Or an array of function pointers which is resized as necessary.

huon
  • 94,605
  • 21
  • 231
  • 225