我正在读一本书,而且没有在线代码参考,所以我不明白两件事。完整代码:
#include <stdio.h>
/* The API to implement */
struct greet_api {
int (*say_hello)(char *name);
int (*say_goodbye)(void);
};
/* Our implementation of the hello function */
int say_hello_fn(char *name) {
printf("Hello %s\n", name);
return 0;
}
/* Our implementation of the goodbye function */
int say_goodbye_fn(void) {
printf("Goodbye\n");
return 0;
}
/* A struct implementing the API */
struct greet_api greet_api = {
.say_hello = say_hello_fn,
.say_goodbye = say_goodbye_fn
};
/* main() doesn't need to know anything about how the
* say_hello/goodbye works, it just knows that it does */
int main(int argc, char *argv[]) {
greet_api.say_hello(argv[1]);
greet_api.say_goodbye();
printf("%p, %p, %p\n", greet_api.say_hello, say_hello_fn, &say_hello_fn);
exit(0);
}我以前从未见过:
int (*say_hello)(char *name);
int (*say_goodbye)(void);以及:
struct greet_api greet_api = {
.say_hello = say_hello_fn,
.say_goodbye = say_goodbye_fn
};我理解那里发生了什么,但正如我之前所说的,我以前从未见过。
在第一个片段中,这些东西都是双括号。等号、点和函数名w/o括号在第二段中。
如果有人能张贴一些好的文章或标题是什么,以便我可以在网上查看,我会真的很感激。
发布于 2014-11-01 23:02:49
前两个是函数指针(How do function pointers work),然后通过指定的初始化器(检查this答案)初始化这两个指针。
发布于 2014-11-01 23:03:01
分别为https://stackoverflow.com/a/840504/3233393和https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html。没有括号的函数名就是将函数的地址存储在函数指针中的方式(在本例中,&是并发的)。
https://stackoverflow.com/questions/26694136
复制相似问题