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.

2
  • 1
    fc_bases[n](params); (and the 3 is not needed in the extern decl.) Commented Apr 16, 2013 at 1:46
  • The question about the function without parameters was irrelevant to the problem itself, so I edited it. Commented Apr 16, 2013 at 1:50

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Both answers solve my question, but the main.c program had declared the structure this way, so it was easier to implement.
If you want some reading practice with function-pointers, I've got some example code here 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.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.