欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C语言的函数指针数组

程序员文章站 2024-02-05 13:18:22
C语言的函数指针数组:概念:数组元素是指针函数的数组叫做指针函数数组,通常我们也叫做转移表定义个初始化:返回类型说明符 (*函数指针数组名[])(参数列表) = {函数指针/函数名...

C语言的函数指针数组:概念:数组元素是指针函数的数组叫做指针函数数组,通常我们也叫做转移表定义个初始化:返回类型说明符 (*函数指针数组名[])(参数列表) = {函数指针/函数名,…};。

如下: int (*fun_array[])(int,int) = {add,del,mul,p};

函数指针数组的使用如下:
函数指针数组名下标或者(*函数指针数组名)下标;
下面是给出的示例代码:

#include

int add(int a,int b); 
int sub(int a,int b); 
int mul(int a,int b); 
int p(int a,int b); 
void make_menu();


int main(int argc,char* argv[]){
    int (*fun_array [])(int,int) = {add,sub,mul,p};
    int cmd = 0;
    int result =  0;  
    int http://blog.csdn.net/qq_29924041/article/details/num1,num2;
    while(1){
        make_menu();
        printf("please select a num what you want :");
        scanf("%d",&cmd);
        if(cmd == 0){ 
            break;
        }else{
            printf("please input two num you want!\n");
            scanf("%d %d",&num1,&num2);
            result = fun_array[cmd-1](http://blog.csdn.net/qq_29924041/article/details/num1,num2);
            printf("the form_1_result you want to calculate is:%d\n",result);
            int (*fun_pointer)(int,int) = fun_array[cmd-1];
            result = fun_pointer(http://blog.csdn.net/qq_29924041/article/details/num1,num2);
            printf("the form_2_result you want to calculate is:%d\n",result);
            result = (*fun_array[cmd-1])(http://blog.csdn.net/qq_29924041/article/details/num1,num2);
            printf("the form_3_result you want to calculate is:%d\n",result);

        }
    }   
    return 0;
}

int add(int a,int b){ 
    return a+b;
}

int sub(int a,int b){ 
    return a - b;
}
int mul(int a,int b){ 
    return a * b;
}

int p(int a,int b){
    return a/b;
}




void make_menu(){
    printf("=====================\n");
    printf("1:add\n");
    printf("2:sub\n");
    printf("3:mul\n");
    printf("4:p\n");
    printf("0:quit\n");
    printf("=====================\n");
}

由上面我们可以看出来函数指针数组的三种调用方式:
int (*pointer)(int ,int ) = fun_array[i];
int result = pointer(http://blog.csdn.net/qq_29924041/article/details/num1,num2);
或者:
int result = fun_arrayi;
或者:
int result =*(fun_array[i])(http://blog.csdn.net/qq_29924041/article/details/num1,num2);
第三种形式我们是不经常会用到的,

结果:

1:add
2:sub
3:mul
4:p

0:quit

please select a num what you want :1
please input two num you want!
10 11
the form_1_result you want to calculate is:21
the form_2_result you want to calculate is:21
the form_3_result you want to calculate is:21

函数指针数组的运用的注意点:

函数的返回类型一样,并且函数的形参也是要一样 通常是在swith函数中去做这样的函数指针数组,便于简化代码。