我看了但找不到这个问题的直接引用。我是函数指针(和 C)的新手,所以我还不知道可以做的所有技巧:)
我实际上得到了一个函数:
void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
...
...其中 My_Struct
有原型(prototype):
typedef struct my_struct {
int (*comp)(int x, int y);
} My_Struct;
取模一些小细节。我只想知道以下语法是否正确:
void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
structure->comp = comp;
}
这似乎太容易了,我很担心。
最佳答案
没有错:这是回调的基础 c .只需确保函数指针的签名与结构中定义的类型相匹配。当你在一个大型项目中使用它时,它变得非常棘手,人们忘记检查函数指针是否有效或 void
,以及参数等。
代码 list
/*******************************************************************************
* Preprocessor directives.
******************************************************************************/
#include <stdio.h>
/*******************************************************************************
* Data types.
******************************************************************************/
typedef struct my_struct {
int (*comp)(int x, int y);
} My_Struct;
/*******************************************************************************
* Function prototypes.
******************************************************************************/
int c(int a, int b);
void select_comparator(My_Struct *structure, int (*comp)(int x, int y));
/*******************************************************************************
* Function definitions.
******************************************************************************/
/*----------------------------------------------------------------------------*/
int main(void)
{
My_Struct s;
select_comparator(&s, &c);
s.comp(1, 2);
return 0;
}
/*----------------------------------------------------------------------------*/
void select_comparator(My_Struct *structure, int (*comp)(int x, int y))
{
structure->comp = comp;
}
/*----------------------------------------------------------------------------*/
int c(int a, int b)
{
int ret = 0;
if (a < b) {
ret = (-1);
} else if (a > b) {
ret = 1;
}
return ret;
}
关于c - 这是将函数传递给结构的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44938557/