c - 我们在哪里可以在 C 中使用函数指针,函数指针有什么用途

标签 c

最近我在一次采访中被问到:我们可以在 C 中的什么地方使用函数指针? 以及返回什么函数指针。我说使用我们可以使用函数指针调用函数然后他问了一些例子但我不能满足他更多的例子。然后他问我函数指针返回什么。我告诉他这取决于函数指针的声明。

但我真的很想知道函数指针在 C 中的一些用法。

最佳答案

我认为 C 中的经典示例是 qsort .从那里引用(我知道它是 http://www.cplusplus.com ,所以一个不是很好的网站,但它似乎是正确的)

void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );

Function that compares two elements. The function shall follow this prototype:

int comparator ( const void * elem1, const void * elem2 ); 

The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.

The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.


另一个“经典”示例是计算器(例如参见 this ,它是 C++ 但在 C 中是相同的)。

例如,你有四个数学函数

float Plus    (float a, float b) { return a+b; }
float Minus   (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide  (float a, float b) { return a/b; }

以某种方式你选择你的操作

/* Here there should be an if or a switch/case that selects the right operation */
float (*ptrFunc)(float, float) = Plus;

你可以稍后调用它(出于某种原因你不想直接在 if/switch 中调用它,也许是因为你想制作其他所有操作“通用”的“东西”,比如日志记录或打印结果)

float result = ptrFunc(1.0f, 2.0f);

你可以使用函数指针的另外两件事是回调(由 vine'th 编写)和“可怜的人”虚函数(你把它们放在 struct 中,当你创建 struct 时(你知道,就像使用“穷人”构造函数一样,但这是 C,因此我们将其称为初始化器),您可以在其中保存 struct 将使用的函数)。

关于c - 我们在哪里可以在 C 中使用函数指针,函数指针有什么用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7281820/

相关文章:

C运行外部程序出现错误

c - C 中从 int 到 char 的类型转换

c - C读取文本文件

c - 按值填充值 a char *

c - 使用带有指向字符的指针的 scanf 函数

c - glPopMatrix() 大喊 "unsupported texture format in setup_hardware_state"

c - 了解 C 宏语法和函数

c - 为什么 getchar() 不能正常工作?

c - C 中的数组增量类型 - array[i]++ 与 array[i++]

c - 复制的字符串是否以 '\0' 结尾(第 1.9 节 C 编程语言 K&R2)