任何人都可以解释以下说明:
int *c[10];
char *(**n)(void);
float *(**r(void))[6];
short *(**v(void))(int);
long *(*(*(*z)(void))[7])(void);
任何人都可以解释以下说明:
int *c[10];
char *(**n)(void);
float *(**r(void))[6];
short *(**v(void))(int);
long *(*(*(*z)(void))[7])(void);
http://www.cdecl.org/将解释所有这些声明。C 左右规则解释了如何很好地阅读 C 声明。还有很多其他可用资源,尤其是在这个问题中。
由于这是你的作业,你不会通过我告诉你一切来学习这个;)但是,一个提示。您可以在 C 中创建和传递指向函数的指针,而不仅仅是变量。
除了第一个例子之外的所有函数参数都是函数指针的原型。
假设我们有一个用于测试颜色的库,我们可能希望允许我们库的用户提供自定义方法来获取颜色的名称。我们可以定义一个结构供用户传入,其中包含我们可以调用的回调。
struct colour_tester {
char *(*colour_callback)(void);
}
// test the user's function if given
void run_test(struct colour_tester *foo ){
// use the callback function if set
if ( foo->colour_callback != NULL ){
char * colour = (*foo->colour_callback)();
printf( "colour callback returned %s\n", colour );
}
}
然后库的用户可以自由定义这些回调函数的实现,并将它们作为函数指针传递给我们。
#include <colour_tester.h>
char * get_shape_colour(){
return "red";
}
int main ( int argc, char** argv ) {
// create a colour tester and tell it how to get the colour
struct colour_tester foo;
foo.colour_callback = &get_shape_colour;
run_test( &foo );
}
我让你去弄清楚那些有额外 *s 的人是怎么回事。