【发布时间】:2019-06-30 03:22:05
【问题描述】:
我不熟悉下面struct的语法
struct fp {
int (*fp)();
}
int (*fp)() 是什么?我知道这是一个 integer 和 *fp 是一个指针,但我不明白 (*fp)() 中的括号是做什么的。
【问题讨论】:
标签: c
我不熟悉下面struct的语法
struct fp {
int (*fp)();
}
int (*fp)() 是什么?我知道这是一个 integer 和 *fp 是一个指针,但我不明白 (*fp)() 中的括号是做什么的。
【问题讨论】:
标签: c
这是一个function pointer。如果您是初学者,它们功能强大且很难理解。
【讨论】:
它是变量 fp 的声明,它是一个 pointer to a function,它返回一个 int 并接受一个 unspecified list of arguments。
【讨论】:
这是一个包装函数指针的结构。
【讨论】:
fp 是指向具有空参数列表的函数的指针。
即
int myfunc() //define function
{
return 0;
}
struct fp //define structure
{
int (*fp)();
} mystruct;
mystruct.fp = &myfunc; //assign function pointer to structure element
int a = mystruct.fp(); //Call function through pointer
有很多方法可以读取 C 声明,在某些情况下可能会非常复杂。开始阅读这个https://parrt.cs.usfca.edu/doc/how-to-read-C-declarations.html。
您可以在 Google 上搜索“如何阅读 c 声明”以获得更深入的解释和更多提示。
正如 Swordfish 所指出的,空参数列表的使用暗示了有关函数定义的其他明智点,这可能值得深入。有关函数定义的要点,请参阅下面 Swordfish 的评论。
我将仅参考 §6.11.6 函数声明符(§6.11 未来语言方向):
使用带空括号的函数声明符(不是 原型格式参数类型声明符)已过时 功能。
【讨论】:
int 的每个函数。但接下来就是默认参数促销:/