gpt4 book ai didi

c - 理解代码片段

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:06 26 4
gpt4 key购买 nike

我正在看书,但没有在线代码引用,所以我不明白几件事。完整代码:

#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
};

我有点了解那里发生了什么,但正如我之前所说,我以前从未见过。

那些东西是第一个片段中的双括号。第二个片段中没有括号的等号、点和函数名称。

如果有人可以发布一些好的文章或标题,以便我可以在线查看,我将不胜感激。

最佳答案

这些分别是function pointersdesignated initializers .不带方括号的函数名称只是将函数地址存储在函数指针中的方式(& 在这种情况下是兼性的)。

关于c - 理解代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com