簡體   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