函数指针是保存函数的内存地址的指针。
如何在C中声明函数指针?
考虑如下函数原型:
void sum ();
根据以上函数原型,函数sum将不带任何参数,并且将不返回任何内容。
因此我们可以声明一个函数指针,如下所示:
void (*fp) ();
这里“*fp”是一个函数指针,它将不接受任何函数参数并返回void。
函数指针将类似于函数原型。
函数指针的更多示例:
int(* fp)(双精度) => “fp”是一个接受double并返回int的函数指针。
无效(* fp)(字符*) => “fp”是一个接受char指针并返回void的函数指针。
double *(* fp)(整数,整数) => “fp”是一个函数指针,它接受两个整数变量并返回一个指向double的指针。
注意:
函数指针应始终写在括号内。
考虑下面的声明:
int *f();
上面是一个简单的函数原型。
考虑下面的声明:
int (*f) ();
上面是一个函数指针,它将不接受任何变量,但返回int变量。
如何在C中使用函数指针?
我们可以利用Pointer来实现回调函数。
如果我们具有如下附加功能:
int add() { return (10+20); }
对于上面的函数,可以如下声明一个函数指针:
int (*fPtr) ();
这里“* fPtr”是一个函数指针,它将不带任何参数并返回整数指针。
现在,您需要将函数分配给该函数指针,如下所示:
fPtr = &add;
现在,您可以按以下方式进行函数调用:
result = (*ptr)();
完整示例:
#include<stdio.h> int add (); int main () { int result; int (*ptr)(); ptr = &add; result = (*ptr)(); printf("The sum is %d\n",result); } int add() { return (5 + 6); }
输出:
The sum is 11
如何传递函数指针?
传递函数指针非常简单。
我们需要创建一个与调用函数匹配的函数指针。
例如:
#include<stdio.h> #include<stdlib.h> int add (int num1, int num2) { return (num1 + num2); } int subtract (int num1, int num2) { return (num1 - num2); } // fptr is a function pointer, that will accept // 2 int values and return a int value typedef int (*fptr) (int, int); // calculate is a function what accepts a function pointer // and it will call appropriate add or subtract function // based 上 the operation value. int calculate(fptr operation, int num1, int num2) { return operation(num1, num2); } int main () { int num1 = 10; int num2 = 20; printf("The num1 = %d, num2 = %d, the addition is = %d\n", num1, num2, calculate(add, num1, num2)); printf("The num1 = %d, num2 = %d, the subtract is = %d\n", num1, num2, calculate(subtract, num1, num2)); return 0; }
输出:
The num1 = 10, num2 = 20, the addition is = 30 The num1 = 10, num2 = 20, the subtract is = -10
如何返回函数指针?
#include<stdio.h> #include<stdlib.h> int add (int num1, int num2) { return (num1 + num2); } int subtract (int num1, int num2) { return (num1 - num2); } // fptr is a function pointer, that will accept // 2 int values and return a int value typedef int (*fptr) (int, int); // select is a function that will return // approprite function pointer // based 上 the opCode fptr select (char opCode) { switch(opCode) { case '+' : return add; case '-' : return subtract; } } // calculate is a function what accepts a operation code as char // and it will call appropriate add or subtract function // based 上 the operation value. int calculate(char opCode, int num1, int num2) { fptr operation = select(opCode); return operation(num1, num2); } int main () { int num1 = 10; int num2 = 20; printf("The num1 = %d, num2 = %d, the addition is = %d\n", num1, num2, calculate('+', num1, num2)); printf("The num1 = %d, num2 = %d, the subtract is = %d\n", num1, num2, calculate('-', num1, num2)); return 0; }
输出:
The num1 = 10, num2 = 20, the addition is = 30 The num1 = 10, num2 = 20, the subtract is = -10