zoukankan      html  css  js  c++  java
  • 42. 函数指针用在菜单驱动系统中,练习函数指针数组的使用。

    函数指针的一个用法出现在菜单驱动系统中。例如程序可以提示用户输入一个整数值来选择菜单中的一个选项。用户的选择可以做函数指针数组的下标,而数组中的指针可以用来调用函数。


    //函数指针数组的使用
    
    #include <stdio.h>
    void func0(int i)
    {
        printf("your enter %d so func%d is called
    ",i,i);
    }
    void func1(int i)
    {
        printf("your enter %d so func%d is called
    ",i,i);
    }
    void func2(int i)
    {
        printf("your enter %d so func%d is called
    ",i,i);
    }
    void func3(int i)
    {
        printf("your enter %d so func%d is called
    ",i,i);
    }
    
    //输入哪个就调哪个函数
    int main(void)
    {
        void (*fpa[4])(int) = {func0,func1,func2,func3};
    
    #if 0  //虽然在这里的switch可有可无,但是以后在项目中不可能用数字代替的,一般是一个单词,或者点击一下窗口中的某一点,然后通过switch来执行相应的函数。
        int choice;
        while(1)
        {
    
            printf("pls input number between o and 3:");
            scanf("%d",&choice);
            switch(choice)
            {
                case 0:
                    fpa[choice](choice);break;
                case 1:
                    fpa[choice](choice);break;
                case 2:
                    fpa[choice](choice);break;
                case 3:
                    fpa[choice](choice);break;
                default:
                    return 0;
            }
        }
    #endif
    
    #if 0 //不使用switch
        int choice;
        while(1)
        {
          printf("pls input number between o and 3:");
          scanf("%d",&choice);
          fpa[choice](choice);
      //  (*fpa[choice])(choice);//这样使用也对,不推荐这样用
        }
    #endif
    
    
    #if 0 //把访问函数指针数组里的元素由上面的数组下标访问形式 改为 指针形式访问 ,需要注意
        int choice;
        while(1)
        {
          printf("pls input number between o and 3:");
          scanf("%d",&choice);
          (*(fpa+choice))(choice);//正确
       // (*fpa)(choice);//错误
     //   (*(*(fpa+choice)))(choice);//这样使用也对,不推荐这样用
        }
    #endif
    
    
        return 0;
    }
  • 相关阅读:
    django修身大法之一阳指
    django修身大法之归天心法
    事务(转账功能)
    el技术,,,,,JSTL技术,,,,,javaEE的开发模式
    DBUtils
    Jquery的Ajax
    实例_一个CSS开门动画
    js_快速判断浏览器是否是IE9以下版本浏览器
    html5_通过网页添加QQ或者加入QQ群
    html5_video&audio的autoplay属性失效的解决方法
  • 原文地址:https://www.cnblogs.com/ZhuLuoJiGongYuan/p/9509953.html
Copyright © 2011-2022 走看看