Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an array of functions in C

Tags:

I have a struct that contains a declaration like this one:

void (*functions[256])(void) //Array of 256 functions without arguments and return value 

And in another function I want to define it, but there are 256 functions! I could do something like this:

struct.functions[0] = function0; struct.functions[1] = function1; struct.functions[2] = function2; 

And so on, but this is too tiring, my question is there some way to do something like this?

struct.functions = { function0, function1, function2, function3, ..., }; 

EDIT: Syntax error corrected as said by Chris Lutz.

like image 877
0x77D Avatar asked Mar 15 '11 09:03

0x77D


People also ask

Can you have an array of functions in C?

Array Functions in C is a type of data structure that holds multiple elements of the same data type. The size of an array is fixed and the elements are collected in a sequential manner. There can be different dimensions of arrays and C programming does not limit the number of dimensions in an Array.

How do you define an array function?

An array can be passed into a function as a parameter. Because an array is not a single item, the array contents are not passed "by value" as we are used to with normal variables. The normal meaning of "pass by value" is that the actual argument value is copied into a local formal parameter variable.

Can there be an array of functions?

An array as a function argument.Arrays are always passed-by-pointer to functions, which means that array arguments can pass data into functions, out of functions, or both in and out of functions.


1 Answers

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)); 
like image 98
Chris Lutz Avatar answered Oct 13 '22 18:10

Chris Lutz