【C】函数指针

函数指针

函数指针是什么

函数指针:就是指向函数的指针,其本质就是一个指针
(函数名就是函数指针,&函数指针)
作用:用来指向函数,调用函数

#include<stdio.h>
int max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    printf("%p\n",max);
    printf("%p\n",&max);
    return 0;
}


我们可以看出max &max的内存地址是一样的

如何创建一个函数指针变量

(*指针名)替换函数名 剩下的照抄,形参名可以省略,这就是函数指针

#include<stdio.h>
int max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    printf("%p\n",max);
    printf("%p\n",&max);
    int (*pder)(int a,int b)=NULL;//pder就是函数指针
    //int (*pder)(int ,int )=NULL;
    pder=max;
    pder=&max;//与  pder=max是等效的
    return 0;
}

在这里插入图片描述

通过函数指针调用函数

  • 直接用指针名替换函数去调用函数
  • (*指针名)替换函数名调用函数
printf("%d\n",pder(2,3));
printf("%d\n",max(2,3));
printf("%d\n",*pder)(2,3));

函数指针一般是用在充当函数的参数(回调函数)

  • 函数:描述一种行为或功能
  • 回调函数的显著特点:一个函数的调用实现不同功能
  • 函数指针只能调用返回值类型和参数类型一致的函数
#include<stdio.h>
int max(int a,int b)
{
    return a>b?a:b;
}
int min(int a,int b)
{
    return a>b?b:a;
}
//以函数指针为参数的指针
void print(int (*pder)(int ,int ),int a,int b)
{
    printf("%d\n",pder(a,b));
}
int main()
{
    int (*pder)(int a,int b)=NULL;//pder就是函数指针
    print(max,1,2);
    print(min,1,2);
    return 0;
}

在这里插入图片描述

typedef与函数指针

  • typedef:给类型起别名
  • typedef与函数指针
#include <stdio.h>


void print(int(*p)(int, int), int a, int b) 
{
	printf("%d\n", p(a, b));
}
//和上面函数一样的
typedef int(*FUNC)(int, int);
void print2(FUNC p, int a, int b)   //FUNC p	 int(*p)(int, int);
{
	printf("%d\n", p(a, b));
}
//typedef 给结构体起别名 后面讲
int main()
{
	//No.1 给基本数据类型起别名
	typedef int 整数;
	int a1 = 1;
	整数 a2 = 1;			//int  a2 = 1
	//typedef unsigned int  size_t;
	size_t a3 = 1;
	//No.2 数组起别名
	typedef int ARRAY[3];
	ARRAY arr = { 1,2,3 };					// int arr[3];   int arr[3];
	for (int i = 0; i < 3; i++) 
	{
		printf("%d\n", arr[i]);
	}
	ARRAY array[3] = { 1,2,3,4,5,6,7,8,9 };	// 等效于int array[3][3];
	typedef int A2D[3][3];
	A2D array2d;							// int array2d[3][3];
	return 0;
}

万能指针充当函数指针

  • 万能指针:使用必须做强制类型转换
  • 指针类型:去掉它的变量名
#include<stdio.h>
void print()
{
    printf("xxx");
}
int main()
{
    void* p=print;//void (*Func)()----->void(*)()
    ((void(*)())p)();
    return 0;
}

void* 指针使用必须做类转换
((指针类型)p)()
void(Func)()—>去掉变量名 Func类型就是:void()()

总结

好了,函数指针的分享就到此结束了。本节的内容基本都是代码块,也比较便于理解吧。如果本节文章存在什么错误的话,还望纠错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是婷婷婷婷呢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值