c - Difference between function with returned type pointer and function pointer
问题描述
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 *);
是具有返回类型的函数的指针struct dentry *
。void
. 首先,您必须为这些指针分配一个实际函数,以通过这些指针调用这些函数。代码中的指针分配有
.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)
是一个返回指针的函数。它已经有一个静态函数体,可以立即调用。
两个调用都返回一个具有相同类型的值struct dentry *
。
函数指针的一大优点是您可以编写通用代码并在运行时为该指针分配不同的函数。常见的用例是诸如排序或查找算法之类的算法,您可以在其中将谓词或比较函数传递给函数指针。
另一个优点是 C 中的结构可以包含函数指针但不能包含函数。这是在 C 中模拟 OOP 的一种方式。
下面是一个函数指针的例子,它指向一个返回指针的函数:
#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);
}
输出:
4 8
推荐阅读
- javascript - 我应该如何处理要删除的对象的事件处理程序?
- plane - 激光雷达数据的 Ransac 地平面分割
- kubernetes - 在私有子网中运行时 AWS EKS 上的 DNS 问题
- android - 如何在 Proguard 中保留 TypeDef?
- html - 如果没有足够的可用空间,则隐藏特定的单词(仅限 CSS)
- c++ - 无法渲染模型 - (glfw / assimp)
- r - 在 R 中运行并行计算时如何在工作人员上设置 .libPaths(检查点)
- python-3.x - Windows 上通过 CMD 安装 Pyaudio 问题
- python - Django - 如何将 DeleteView 限制为对象所有者
- django - 如何在不明确填写 PasswordResetForm 的情况下向用户发送电子邮件以重置密码?