c - 解释一下C语言中的函数指针

标签 c function-pointers

C中最基本的函数指针是如何创建的?

最佳答案

这是一个非常简单的示例:

#include <stdio.h>
#include <string.h>

int add(int x, int y) {
    return x + y;
}

int sub(int x, int y) {
    return x - y;
}

int main() {
    char const * operator = "addition";

    int (*operation)(int, int) = NULL;
    if (strcmp(operator, "subtract") == 0)
        operation = sub;
    if (strcmp(operator, "addition") == 0)
        operation = add;

    if (operation) {
        int x = 3;
        int y = 7;
        int z = operation(x, y);
        printf("%s %d %d == %d\n", operator, x, y, z);
    }
}

这有什么用处?

我见过的一个常见用例是创建接口(interface)。例如,我们有一种对象类型,例如表示网络接口(interface)的结构。现在,由于有不同的硬件后端,我们可能希望根据硬件实现来实现不同的功能。

所以我们可能在接口(interface)结构体中有一个函数指针,用于初始化硬件、发送数据包和接收数据包。

关于c - 解释一下C语言中的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26144309/

相关文章:

c++ - 如何向 C 窗口中的几个对等点发送多播消息

c - 算法设计手册,第三章,链表代码片段混淆

java - 包含用于参数传递的方法/函数的数组

c - 在不使用标准函数的情况下在 C 中生成正弦信号

php 5.3 和 APC(发生了什么)?

c - 如何理解void (*action)(struct softirq_action *)

c - Eclipse Juno、CDT、ARM、OS X 上的路径问题

c - 为什么使用回调而不是普通的函数调用?

c - C 中的牛顿拉夫函数指针

c++ - 将指定函数赋值给函数成员指针?