注册 登录
电子工程世界-论坛 返回首页 EEWORLD首页 频道 EE大学堂 下载中心 Datasheet 专题
DreamStreaking的个人空间 https://home.eeworld.com.cn/space-uid-702851.html [收藏] [复制] [分享] [RSS]
日志

一个函数指针的例子--int (* FunctionFound(char op))(int ,int) ;

已有 911 次阅读2018-3-6 14:12 |个人分类:C| 函数指针

/*******************************************
 * this file is to test function pointer
 *
 *******************************************/
#include <stdio.h>


typedef int(*FP_CALL)(int,int);  //Defines a function pointer type


int (*data_return)(int);  // Defines a function pointer of  global type

int DataReturn(int a)
{
  return a;
}

int AddCaculate(int a,int b)
{
return (a + b);
}
FP_CALL CallFunction(char op)
{
switch(op)
{
case '+' : 
printf("found the function AddCaculate \n");
return AddCaculate;
break;
default :
printf("the input error\n");
}
}
int (* FunctionFound(char op))(int ,int) // this is a function whose return data is a function pointer;
{
return CallFunction(op);
}

void main()
{
FP_CALL function_call;
int *p;
int a = 100;
data_return = DataReturn;
p = &a;
function_call = FunctionFound('+');
printf("hello my honey!!!\n");
printf("the function pointer data_return  address  is : %d \n",data_return);
printf("the function pointer *data_return address  is : %d \n",*data_return);
printf("the (*data_return)(2) result is : %d .\n",(*data_return)(2));
printf("the   data_return(3)  result is : %d .\n",data_return(3));

printf("the int pointer (*p) is : %d \n",*p);
printf("the int pointer p is : %d \n",p);
printf("the function_call run result is :%d \n",function_call(10,12));
/*  */
}
//运行结果: 本例子是再windows上建立GCC,利用gcc命令进行编译的;

分析:
  1、typedef int(*FP_CALL)(int,int);   //定义一个函数指针类型,并不是一个函数指针;
        FP_CALL function_call;   // 这一句才是定义一个函数指针;
  2、  int (*data_return)(int);    // 这个是直接定义一个函数指针;与1中,只是定义方法不同;
  3、FP_CALL CallFunction(char op)    //此函数的返回值为一个函数指针;
  4、int (* FunctionFound(char op))(int ,int)  // 此函数的返回值也是一个函数指针;此函数指针拥有两个int参数,返回值类型为int;
  5、data_return 和 *data_return 定义的地址是一样的;也就是说data_return(2);与(*data_return)(2);都可以调用函数指针所指向的函数;
全部作者的其他最新日志
评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册

热门文章