2013-04-16 111 views
1

我在我的程序中有以下文件,一个包含特定函数定义的头文件和一个包含函数体的程序。使用指针数组调用函数

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 */ 

注意,在标题我已经定义函数指针阵列,并且在something.c程序,所述函数与数组的每个元素相关联。

假设在某个时刻我需要在main.c程序中调用所有3个函数。有了这个,我可以如何使用extern数组指针在我的main.c中调用这个函数。

+1

'fc_bases [n](params);'(并且'extern' decl中不需要'3')。 – WhozCraig

+0

关于没有参数的函数的问题与问题本身无关,所以我编辑了它。 – SealCuadrado

回答

1

当你打电话时,函数指针会自动解除引用,所以它就像

foo f; 
fc_bases[0](&f); 
fc_bases[1](&f); 
fc_bases[2](&f); 
+0

这两个答案都解决了我的问题,但是'main.c'程序以这种方式声明了结构,所以它更容易实现。 – SealCuadrado

+0

如果你想用函数指针进行一些阅读练习,我已经有了一些示例代码[here](http://stackoverflow.com/questions/6635851/real-world-use-of-x-macros/6636596#6636596 ),将它们放在一个由'enum'索引的数组中,并与宏绑定在一起。我也有他们在一个有限状态机的结构数组[这里](http://stackoverflow.com/questions/1647631/c-state-machine-design/6758622#6758622)。 –

1

如果f1被声明为结构foo的结构的指针变量如下,

foo *f1; 

然后可以首先()和第二()如下调用的函数,

pointer_fc fc_bases[] = {first, second}; 

(*fc_bases[0])(f1); 

(*fc_bases[1])(f1);