1

I have the following files in my program, a header with certain function definitions, and a program with the body of the functions.

something.h

typedef struct _foo {
 int id;
 int lucky_number;
} foo;

typedef void (*pointer_fc)(foo *);

void first(foo *);

void second(foo *);

void third(foo *);

extern pointer_fc fc_bases[3];

something.c

pointer_fc fc_bases[] = {first, second, third};

/* body of functions */

Note that in the header I had defined an array of pointers to functions, and in the something.c program, the functions are associated with every element of the array.

Let's suppose in certain moment I need in the main.c program to call all 3 functions. With this, how I can use the extern array of pointers to call this functions in my main.c.

SealCuadrado
  • 749
  • 1
  • 10
  • 21

2 Answers2

1

If f1 is declared as follows as a structure pointer variables of the structure foo,

foo *f1;

Then you can call the functions first() and second() as follows,

pointer_fc fc_bases[] = {first, second};

(*fc_bases[0])(f1);

(*fc_bases[1])(f1);
Deepu
  • 7,592
  • 4
  • 25
  • 47
1

Function pointers are automatically dereferenced when you call them, so it's as simple as

foo f;
fc_bases[0](&f);
fc_bases[1](&f);
fc_bases[2](&f);
luser droog
  • 18,988
  • 3
  • 53
  • 105
  • Both answers solve my question, but the `main.c` program had declared the structure this way, so it was easier to implement. – SealCuadrado Apr 16 '13 at 02:11
  • If you want some reading practice with function-pointers, I've got some example code [here](http://stackoverflow.com/questions/6635851/real-world-use-of-x-macros/6636596#6636596) that puts them in an array indexed by an `enum`, tied together with macros. I've also got them in arrays of structs for a finite-state machine [here](http://stackoverflow.com/questions/1647631/c-state-machine-design/6758622#6758622). – luser droog Apr 16 '13 at 04:31