函数指针

顾名思义,指针函数即返回指针的函数。其一般定义形式如下:

      类型名 *函数名(函数参数表列);

    其中,后缀运算符括号“()”表示这是一个函数,其前缀运算符星号“*”表示此函数为指针型函数,其函数值为指针,即它带回来的值的类型为指针,当调用这个函数后,将得到一个“指向返回值为…的指针(地址),“类型名”表示函数返回的指针指向的类型”。

    “(函数参数表列)”中的括号为函数调用运算符,在调用语句中,即使函数不带参数,其参数表的一对括号也不能省略。其示例如下:

    int *pfun(int, int);

    由于“*”的优先级低于“()”的优先级,因而pfun首先和后面的“()”结合,也就意味着,pfun是一个函数。即:

    int *(pfun(int, int));

    接着再和前面的“*”结合,说明这个函数的返回值是一个指针。由于前面还有一个int,也就是说,pfun是一个返回值为整型指针的函数。

    我们不妨来再看一看,指针函数与函数指针有什么区别?

    int (*pfun)(int, int);

    通过括号强行将pfun首先与“*”结合,也就意味着,pfun是一个指针,接着与后面的“()”结合,说明该指针指向的是一个函数,然后再与前面的int结合,也就是说,该函数的返回值是int。由此可见,pfun是一个指向返回值为int的函数的指针。

    虽然它们只有一个括号的差别,但是表示的意义却截然不同。函数指针的本身是一个指针,指针指向的是一个函数。指针函数的本身是一个函数,其函数的返回值是一个指针。

2.    用函数指针作为函数的返回值

    在上面提到的指针函数里面,有这样一类函数,它们也返回指针型数据(地址),但是这个指针不是指向int、char之类的基本类型,而是指向函数。对于初学者,别说写出这样的函数声明,就是看到这样的写法也是一头雾水。比如,下面的语句:

    int (*ff(int))(int *, int);

我们用上面介绍的方法分析一下,ff首先与后面的“()”结合,即:

    int (*(ff(int)))(int *, int);                            // 用括号将ff(int)再括起来

也就意味着,ff是一个函数。

    接着与前面的“*”结合,说明ff函数的返回值是一个指针。然后再与后面的“()”结合,也就是说,该指针指向的是一个函数。

这种写法确实让人非常难懂,以至于一些初学者产生误解,认为写出别人看不懂的代码才能显示自己水平高。而事实上恰好相反,能否写出通俗易懂的代码是衡量程序员是否优秀的标准。一般来说,用typedef关键字会使该声明更简单易懂。在前面我们已经见过:

    int (*PF)(int *, int);

也就是说,PF是一个函数指针“变量”。当使用typedef声明后,则PF就成为了一个函数指针“类型”,即:

    typedef int (*PF)(int *, int);

这样就定义了返回值的类型。然后,再用PF作为返回值来声明函数:

    PF ff(int);

   下面将以程序清单1为例,说明用函数指针作为函数的返回值的用法。当程序接收用户输入时,如果用户输入d,则求数组的最大值,如果输入x,则求数组的最小值,如果输入p,则求数组的平均值。

程序清单 1  求最值与平均值示例

1       #include<stdio.h>

2       #include <assert.h>

3       double GetMin(double *dbData, int iSize)               // 求最小值

4       {

5           double dbMin;

6           int i;

7      

8           assert(iSize>0);

9           dbMin=dbData[0];

10          for (i=1; i<iSize; i++){

11                if (dbMin>dbData[i]) {

12                     dbMin=dbData[i];

13                }

14          }

15          return dbMin;

16     }

17

18     double GetMax(double *dbData, int iSize)                 // 求最大值

19     {

20         double dbMax;

21         int i;

22

23         assert(iSize>0);

24         dbMax=dbData[0];

25         for (i=1; i<iSize; i++){

26             if (dbMax< dbData[i]) {

27                 dbMax=dbData[i];

28             }

29         }

30         return dbMax;

31     }

32

33     double GetAverage(double *dbData, int iSize)            // 求平均值

34     {

35         double dbSum=0;

36         int i;

37    

38         assert(iSize>0);

39         for (i=0; i<iSize; i++)

40         {

41              dbSum+=dbData[i];

42         }

43         return dbSum/iSize;

44     }

45

46     double UnKnown(double *dbData, int iSize)             // 未知算法

47     {

48         return 0;

49     }

50

51     typedef double (*PF)(double *dbData, int iSize);     // 定义函数指针类型

52     PF GetOperation(char c)                              // 根据字符得到操作类型,返回函数指针

53     {

54         switch (c)

55         {

56           case 'd':

57                     return GetMax;

58           case 'x':

59                     return GetMin;

60           case 'p':

61                     return GetAverage;

62           default:

63                     return UnKnown;

64           }

65     }

66

67     int main(void)

68     {

69          double dbData[]={3.1415926, 1.4142, -0.5,999, -313, 365};

70          int iSize=sizeof(dbData)/sizeof(dbData[0]);

71          char c;

72

73          printf("Please input the Operation :\n");

74          c=getchar();

75          printf("result is %lf\n", GetOperation(c)(dbData,iSize));   // 通过函数指针调用函数

76    }

    上述程序中前面4个函数分别实现求最大值、最小值、平均值和未知算法,然后实现了GetOperation函数。这个函数根据字符的返回值实现上面4个函数。它是以函数指针的形式返回的,从后面的main函数的GetOperation(c)(dbData, iSize)可以看出,通过这个指针可以调用函数。

转载于:https://www.cnblogs.com/nktblog/archive/2013/02/20/2918084.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/274359.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

orton效果_如何使图片发光:Orton效果

orton效果Have you ever seen an impossibly dream-like landscape photo? One with a slow burning, glowing sunset. That’s really the best way to describe it, the image looks as if it’s glowing. You might be thinking, “wow, I wish I was that good and could …

UVA10785 The Mad Numerologist

虽然是sorting的压轴&#xff0c;但是比起前面真心水题。这个专题结合前面string的很多&#xff0c;排序相对简单了&#xff0c;qsort基本解决。 题目&#xff1a; The Mad Numerologist Numerology is a science that is used by many people to find out a mans personality,…

苹果人机交互指南_苹果人机界面设计指南的10个见解

苹果人机交互指南重点 (Top highlight)I’ve been developing an IOS app for the past few months and have been constantly referring to Apple’s Human Interface Design Guidelines. I would consider it a must-read for any aspiring or current UI/UX designer.在过去…

也来学学插件式开发

上一家公司有用到插件式开发来做一个工具箱&#xff0c;类似于QQ电脑管家&#xff0c;有很多工具列表&#xff0c;点一下工具下载后就可以开始使用了。可惜在那家公司待的时候有点短&#xff0c;没有好好研究一下。现在有空&#xff0c;自己在网上找了些资料&#xff0c;也来试…

同态加法_我对同态的想法

同态加法Early February, I uploaded this shot onto Dribbble. Nothing fancy –– just two screens experimenting with “2月初&#xff0c;我将这张照片上传到Dribbble。 没什么幻想–只有两个屏幕在尝试“ Neumorphism,” or soft UI. Little did I know that this post…

php内核探索

引自&#xff1a;http://www.nowamagic.net/librarys/veda/detail/1285 SAPI:Server Application Programming Interface 服务器端应用编程端口。研究过PHP架构的同学应该知道这个东东的重要性&#xff0c;它提供了一个接口&#xff0c;使得PHP可以和其他应用进行交互数据。 本…

hp-ux锁定用户密码_UX设计101:用户研究-入门需要了解的一切

hp-ux锁定用户密码这是什么&#xff1f; (What is this?) This session is part of a learning curriculum that I designed to incrementally skill up and empower a team of Designers and Researchers whose skillset and ways of working needed to evolve to keep up wi…

等比数列前N项和的公式推导

设等比数列的前n项和为S(n), 等比数列的第一项为a1&#xff0c;比值为q。 &#xff08;1&#xff09;S(n) a1 a1 * q a1 * q ^ 2 .... a1 * q ^ (n - 1);&#xff08;2&#xff09;S(n1) a1 a1 * q a1 * q ^ 2 .... a1 * q ^ (n - 1) a1 * q ^ n;由&#xff08;2&am…

extjs6 引入ux_关于UX以及如何摆脱UX的6种常见误解

extjs6 引入uxDo you ever browse social media, internet, or talk to colleagues and hear them say something UX related you disagree with so much that you just want to lecture them on the spot?您是否曾经浏览过社交媒体&#xff0c;互联网或与同事交谈&#xff0c…

Cocos2D-HTML5开源2D游戏引擎

http://www.programmer.com.cn/12198/ Cocos2D-HTML5是基于HTML5规范集的Cocos2D引擎的分支&#xff0c;于2012年5月发布。Cocos2D-HTML5的作者林顺将在本文中介绍Cocos2D-HTML5的框架、API、跨平台能力以及强大的性能。Cocos2D-HTML5是Cocos2D系列引擎随着互联网技术演进而产生…

illustrator下载_Illustrator笔工具练习

illustrator下载Adobe Illustrator is a fantastic vector creation tool and you can create a lot of things without ever using the Pen Tool. However, if you want to use Illustrator at its full potential, I personally believe that you need to master and become …

怎么更好练习数位板_如何设计更好的仪表板

怎么更好练习数位板重点 (Top highlight)Dashboard noun \ˈdash-ˌbȯrd\ A screen on the front of a usually horse-drawn vehicle to intercept water, mud, or snow.仪表盘 名词\ ˈdash-ˌbȯrd \\通常在马拉的车辆前部的屏幕&#xff0c;用来拦截水&#xff0c;泥或雪。…

学习正则表达式

deerchao的blog Be and aware of who you are. 正则表达式30分钟入门教程 来园子之前写的一篇正则表达式教程&#xff0c;部分翻译自codeproject的The 30 Minute Regex Tutorial。 由于评论里有过长的URL,所以本页排版比较混乱,推荐你到原处查看,看完了如果有问题,再到这里来提…

人物肖像速写_去哪儿? 优步肖像之旅

人物肖像速写In early 2018, the Uber brand team started a rebranding exercise, exploring a fresh take on what it means to be a global transportation and technology company. A new logo was developed in tandem with a bespoke sans-serif typeface called Uber Mo…

js获取和设置属性

function square(num){ var total num*num;//局部变量 return total;}var total 50;//全局变量var number square(20);alert(total);//结果为50function square(num){ total num*num;//全局变量 return total;}var total 50;//全局变量var number square(20)…

hp-ux锁定用户密码_我们如何简化925移动应用程序的用户入门— UX案例研究

hp-ux锁定用户密码Prologue: While this is fundamentally a showcase of our process in the hopes of helping others, it’s also a story about the realism of limitations when working with clients and how we ultimately were able to deliver a product the client w…

微信公众号无需二次登录_您无需两次解决问题-您需要一个设计系统

微信公众号无需二次登录重点 (Top highlight)The design system concept can be differently defined according to each person’s background. Designers may say that a design system is a style guide while developers may say it is UI standards, or specs, or even as…

android中AsyncTask和Handler对比

1 &#xff09; AsyncTask实现的原理,和适用的优缺点 AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程. 使用的优点: l 简单,快捷 l 过程可…

视觉工程师面试指南_选择正确视觉效果的终极指南

视觉工程师面试指南When it comes to effective data visualization, the very first and also the most critical step is to select the right graph/visual for the data that you want to present. With a wide range of visualization software that is available offerin…

在 Linux 下使用 水星MW150cus (RTL8188CUS芯片)无线网卡

Fedora &#xff08;如果你不使用 PAE 内核&#xff0c;请去掉 PAE 字样&#xff09;:yum install gcc kernel-PAE kernel-PAE-devel kernel-headers dkms Ubuntu: apt-get install make gcc linux-kernel-devel linux-headers-uname -r安装原生驱动 注意&#xff1a;由于在 Li…