张赐荣——一位视障程序员。
赐荣小站: www.prc.cx

張賜榮

张赐荣的技术博客

博客园 首页 新随笔 联系 订阅 管理

指向无参函数的指针

#include <stdio.h>
int Integer(void);
char Char(void);
int main(void)
{
int (*a)() = Integer;
char (*b)() = Char;;
printf("%d\n%c\n",a(),b());
a = Char;
b = Integer;
printf("%d\n%c\n",b(),a());
return 0;
}
int Integer(void)
{
return 5;
}
char Char(void)
{
return 'A';
}

/*
定义函数指针的格式是
函数返回值类型 (*指针变量名)();
因为在定义指针变量时,变量名用圆括号括了起来,由此编译器认为该指针变量是函数指针变量;
函数名表示函数的首地址,把函数的首地址付给函数指针变量,就可以通过函数指针变量来调用函数。
给函数指针变量付值的格式是:
函数指针变量名 = 函数名;
通过函数指针变量调用所指向的函数的格式是:
函数指针变量名();
无参函数指针变量可以指向返回值不同于该指针变量的类型的函数,同样可以正常调用。
*/


指向有参函数的指针

#include <stdio.h>
int max(int,int);
int plus(int,int);
int main(void)
{
int (*p)(int,int) = max;
printf("%d\n",p(3,2));
p = plus;
printf("%d\n",p(100,200));
return 0;
}
int max(int a,int b)
{
int o = 0;
if(a == b)
return 0;
if(a < b)
o = a;
a = b;
b = o;
return a;
}
int plus(int a,int b)
{
return a+b;
}

/*
严格的说,定义函数指针变量的格式是:
函数返回值类型 (*函数指针变量名)(函数形参列表);
在定义函数指针变量时,就决定了该函数指针变量能指向怎样的函数,该函数指针变量只能指向与定义时相同函数圆形的函数;
在本例中,函数max与函数plus的圆形一样,并且函数指针变量p所能指向的函数的圆形与max和plus也一样,所以函数指针变量p可以随意指向这两个函数,并能正常调用。
*/

posted on 2022-03-21 16:04  张赐荣  阅读(102)  评论(0编辑  收藏  举报

感谢访问张赐荣的技术分享博客!
博客地址:https://cnblogs.com/netlog/
知乎主页:https://www.zhihu.com/people/tzujung-chang
个人网站:https://prc.cx/