c - 这是将函数传递给结构的正确方法吗?

标签 c function-pointers

我看了但找不到这个问题的直接引用。我是函数指针(和 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;
}

这似乎太容易了,我很担心。

最佳答案

没有错:这是回调的基础 .只需确保函数指针的签名与结构中定义的类型相匹配。当你在一个大型项目中使用它时,它变得非常棘手,人们忘记检查函数指针是否有效或 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/

相关文章:

python - 将bytearray从Python传输到C并返回

c++ - 取函数模板重载的地址

C memcpy() 一个函数

c++ - 动态整数大小 : int64_t, int32_t、uint32_t 等

C - 数独求解器 - 帮助理解函数

c - 段。打印字符时出错

c - 如何分配和调整int***数组的内存大小?

C:计算文件中大写/小写字符的数量

c++ - 在 vector 中调用函数指针不会做任何事情

c++ - 指向函数成员的已删除指针的类型