繁体   English   中英

带返回类型指针的 function 和 function 指针之间的区别

[英]Difference between function with returned type pointer and function pointer

我有一个结构定义的代码,其中成员 function 指针像这样

    struct file_system_type {
        
        struct dentry *(*mount) (struct file_system_type *, int,
                   const char *, void *);
        void (*kill_sb) (struct super_block *);
        
    };

file_system_type的 object 像这样

    static struct file_system_type minix_fs_type = {
        .mount      = minix_mount,
        .kill_sb    = kill_block_super,
        
    };

.mount像这样

    static struct dentry *minix_mount(struct file_system_type *fs_type,
     int flags, const char *dev_name, void *data)

我想知道上面与 function 有什么区别,返回类型是一些指针,就像我有这样的东西

    static struct dentry* minix_mount(...)
struct dentry *(*mount) (struct file_system_type *, int,
               const char *, void *);
void (*kill_sb) (struct super_block *);

是指针 function 具有返回类型struct dentry * resp。 void 首先,您必须为这些指针分配一个实际的 function 以通过这些指针调用这些函数。 代码中的指针分配有

    .mount      = minix_mount,
    .kill_sb    = kill_block_super,
static struct dentry *minix_mount(struct file_system_type *fs_type,
 int flags, const char *dev_name, void *data)

是一个返回指针的 function。 它已经有一个 static function 主体,可以立即调用。

两个调用都返回一个具有相同类型struct dentry *的值。

function 指针的一大优势是您可以编写通用代码并在运行时为该指针分配不同的函数。 常见的用例是排序或查找算法等算法,您可以在其中传递谓词或将 function 与 function 指针进行比较。

另一个优点是 C 中的结构可以包含 function 指针但不能包含函数。 这是在 C 中模拟 OOP 的一种方法。

下面是一个指向 function 的 function 指针返回一个指针的示例:

#include <stdio.h>

struct S {
    int x;
    int y;
    // pointers to functions returning a pointer
    int *(*compare1)(int *, int *);
    int *(*compare2)(int *, int *);
};

// functions returning a pointer
int *min(int *a, int *b) {
    return *a < *b ? a : b;
}

int *max(int *a, int *b) {
    return *a > *b ? a : b;
}

int main() {
    struct S s = {
        .x = 5,
        .y = 7,
        .compare1 = &max,
        // .compare2 = &min;
        // name of a function can be used as function pointer
        .compare2 = min
    };
    int *result1 = s.compare1(&s.x, &s.y);
    int *result2 = s.compare2(&s.x, &s.y);
    ++*result1;
    --*result2;
    printf("%d %d", s.x, s.y);
}

Output:

4 8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM