I have a code with struct defination with member function pointers like this
struct file_system_type {
struct dentry *(*mount) (struct file_system_type *, int,
const char *, void *);
void (*kill_sb) (struct super_block *);
};
and object of file_system_type
like this
static struct file_system_type minix_fs_type = {
.mount = minix_mount,
.kill_sb = kill_block_super,
};
and .mount
like this
static struct dentry *minix_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
I like to know what is the difference of above from function with return type some pointer like if I had something like this
static struct dentry* minix_mount(...)
struct dentry *(*mount) (struct file_system_type *, int,
const char *, void *);
void (*kill_sb) (struct super_block *);
are pointers a function that have return type struct dentry *
resp. void
. First you have to assign an actual function to these pointers to call these functions through these pointer. The pointers in your code are assigned with
.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)
is a function that returns a pointer. It already has a static function body and can instantly be called.
Both calls return a value with the same type struct dentry *
.
A big advantage of function pointers is that you can write generic code and assign a different functions to this pointer at run time. Common use-cases are algorithms like sort or find algorithms where you can pass a predicate or compare function to a function pointer.
Another advantage is that structs in C can contain function pointers but can't contain functions. That's a way to simulate OOP in C.
Here is an example of a function pointer to a function returning a pointer:
#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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.