-
MYYA
你有一个很好的例子(函数指针数组),语法详细。int sum(int a, int b);int subtract(int a, int b);int mul(int a, int b);int div(int a, int b);int (*p[4]) (int x, int y);int main(void){
int result;
int i, j, op;
p[0] = sum; /* address of sum() */
p[1] = subtract; /* address of subtract() */
p[2] = mul; /* address of mul() */
p[3] = div; /* address of div() */[...]要调用其中一个函数指针:result = (*p[op]) (i, j); // op being the index of one of the four functions
-
波斯汪
以上答案可能对您有所帮助,但您可能也想知道如何使用函数指针数组。void fun1(){}void fun2(){}void fun3(){}void (*func_ptr[3]) = {fun1, fun2, fun3};main(){
int option;
printf("\nEnter function number you want");
printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
scanf("%d",&option);
if((option>=0)&&(option<=2))
{
(*func_ptr[option])();
}
return 0;}您只能将具有相同返回类型和相同参数类型且没有参数的函数的地址分配给单个函数指针数组。如果所有上述函数具有相同数量的相同类型的参数,您也可以传递如下所示的参数。 (*func_ptr[option])(argu1);注意:在数组中,函数指针的编号将从0开始,与一般数组相同。因此,fun1如果option = 0,fun2可以调用上面的示例,如果option = 1 fun3则可以调用,如果option = 2则可以调用。
-
汪汪一只猫
以下是如何使用它:New_Fun.h#ifndef NEW_FUN_H_#define NEW_FUN_H_#include <stdio.h>typedef int speed;speed fun(int x);enum fp {
f1, f2, f3, f4, f5};void F1();void F2();void F3();void F4();void F5();#endifNew_Fun.c#include "New_Fun.h"speed fun(int x){
int Vel;
Vel = x;
return Vel;}void F1(){
printf("From F1\n");}void F2(){
printf("From F2\n");}void F3(){
printf("From F3\n");}void F4(){
printf("From F4\n");}void F5(){
printf("From F5\n");}MAIN.C#include <stdio.h>#include "New_Fun.h"int main(){
int (*F_P)(int y);
void (*F_A[5])() = { F1, F2, F3, F4, F5 }; // if it is int the pointer incompatible is bound to happen
int xyz, i;
printf("Hello Function Pointer!\n");
F_P = fun;
xyz = F_P(5);
printf("The Value is %d\n", xyz);
//(*F_A[5]) = { F1, F2, F3, F4, F5 };
for (i = 0; i < 5; i++)
{
F_A[i]();
}
printf("\n\n");
F_A[f1]();
F_A[f2]();
F_A[f3]();
F_A[f4]();
return 0;}我希望这有助于理解 Function Pointer.