How to define an array of functions in C
I have a struct that contains a declaration like this one:
No you don't. That's a syntax error. You're looking for:
void (*functions[256])();
Which is an array of function pointers. Note, however, that void func()
isn't a "function that takes no arguments and returns nothing." It is a function that takes unspecified numbers or types of arguments and returns nothing. If you want "no arguments" you need this:
void (*functions[256])(void);
In C++, void func()
does mean "takes no arguments," which causes some confusion (especially since the functionality C specifies for void func()
is of dubious value.)
Either way, you should typedef
your function pointer. It'll make the code infinitely easier to understand, and you'll only have one chance (at the typedef
) to get the syntax wrong:
typedef void (*func_type)(void);// ...func_type functions[256];
Anyway, you can't assign to an array, but you can initialize an array and copy the data:
static func_type functions[256] = { /* initializer */ };memcpy(mystruct.functions, functions, sizeof(functions));
I had the same problem, this is my small program to test the solution. It looks pretty straightforward so I thought I'd share it for future visitors.
#include <stdio.h>int add(int a, int b) { return a+b;}int minus(int a, int b) { return a-b;}int multiply(int a, int b) { return a*b;}typedef int (*f)(int, int); //declare typdeff func[3] = {&add, &minus, &multiply}; //make array func of type f, //the pointer to a functionint main() { int i; for (i = 0; i < 3; ++i) printf("%d\n", func[i](5, 4)); return 0;}
You can do it dynamically... Here is a small example of a dynamic function array allocated with malloc...
#include <stdio.h>#include <stdlib.h>typedef void (*FOO_FUNC)(int x);void a(int x){ printf("Function a: %d\n", x);}void b(int x){ printf("Function b: %d\n", x);}int main(int argc, char **argv){ FOO_FUNC *pFoo = (FOO_FUNC *)malloc(sizeof(FOO_FUNC) * 2); pFoo[0] = &a; pFoo[1] = &b; pFoo[0](10); pFoo[1](20); return 0;}