登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

函数指针学习与理解  

2006-08-01 22:36:27|  分类: C/C++ |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
//函数指针学习与理解

/*
Makefile:
-------------------------------
callback.exe : callback.c
    gcc callback.c -o callback.exe
clean:
    rm callback.exe
*/


#include <stdio.h>
#include <stdlib.h>

//函数指针类型的声明
typedef int (*CallBackHandle)(int a, int b);

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

//全局的函数指针
CallBackHandle handle;

//作业处理函数
void process()
{
    printf("Please input two number:\n");
    int a,b;
    scanf("%d", &a);
    scanf("%d", &b);
    printf("\n%d op %d is ", a, b);
    if(handle != NULL)
        printf("%d\n", handle(a, b));
    else
        printf("unknow\n");
}
//初始化全局函数指针
void iniHandle()
{
redo:
    printf("Please select a op function:\n");
    printf("Add     1\n");
    printf("Minus   2\n");
    int k;
    scanf("%d", &k);
    switch(k)
    {
        case 1:
        handle = add;
        printf("Add selected.\n");
        break;
        case 2:
        handle = minus;
        printf("Minus selected.\n");
        break;
        default:
        printf("Function Select Error!\n");
        goto redo;
    }
}
//初始化全局函数指针的另外一个版本
void iniHandle_2()
{
    printf("add:  %d\n", add);
    printf("minus:%d\n", minus);
    
    int addr = 0;
    scanf("%d", &addr);
    handle = (void*)addr;
    printf("Now the handle is %d\n", handle);   
}

//程序入口点
int main()
{
    iniHandle_2();
    process();   
}
 
  评论这张
 
阅读(927)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018