Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How define an array of function pointers in C

I've a little question. I'm trying to define an array of function pointers dynamically with calloc. But I don't know how to write the syntax. Thanks a lot.

like image 235
strstr Avatar asked Mar 30 '11 15:03

strstr


People also ask

How do you declare an array of a function pointer?

int sum(int a, int b); int subtract(int a, int b); int mul(int a, int b); int div(int a, int b); int (*p[4]) (int x, int y); int main(void) { int result; int i, j, op; p[0] = sum; /* address of sum() */ p[1] = subtract; /* address of subtract() */ p[2] = mul; /* address of mul() */ p[3] = div; /* address of div() */ [. ...

Is array of function pointer possible in C?

In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.


2 Answers

The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to:

int foo( int )

would be:

int (*)( int )

In order to name an instance of this type, put the name inside (*), after the star, so:

int (*foo_ptr)( int )

declares a variable called foo_ptr that points to a function of this type.

Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so:

int (*foo_ptr_array[2])( int )

declares a variable called foo_ptr_array which is an array of 2 function pointers.

The syntax can get pretty messy, so it's often easier to make a typedef to the function pointer and then declare an array of those instead:

typedef int (*foo_ptr_t)( int );
foo_ptr_t foo_ptr_array[2];

In either sample you can do things like:

int f1( int );
int f2( int );
foo_ptr_array[0] = f1;
foo_ptr_array[1] = f2;
foo_ptr_array[0]( 1 );

Finally, you can dynamically allocate an array with either of:

int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) );
foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) );

Notice the extra * in the first line to declare a1 as a pointer to the function pointer.

like image 76
Andrew Eidsness Avatar answered Oct 11 '22 12:10

Andrew Eidsness


I put a small example here that may help you

typedef void (*fp)(int); //Declares a type of a void function that accepts an int

void test(int i)
{
    printf("%d", i);
}

int _tmain(int argc, _TCHAR* argv[])
{
    fp function_array[10];  //declares the array

    function_array[0] = test;  //assings a function that implements that signature in the first position

    function_array[0](10); //call the cuntion passing 10

}
like image 5
Andres Avatar answered Oct 11 '22 14:10

Andres