C语言的函数指针数组

2017-01-04 12:02:52来源:作者:人点击

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

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

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

#includeint add(int a,int b); int sub(int a,int b); int mul(int a,int b); int div(int a,int b); void make_menu();int main(int argc,char* argv[]){    int (*fun_array [])(int,int) = {add,sub,mul,div};    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 div(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:div/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:div

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函数中去做这样的函数指针数组,便于简化代码。

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台