函数指针
函数指针是什么
函数指针:就是指向函数的指针,其本质就是一个指针
(函数名就是函数指针,&函数指针)
作用:用来指向函数,调用函数
#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()()
总结
好了,函数指针的分享就到此结束了。本节的内容基本都是代码块,也比较便于理解吧。如果本节文章存在什么错误的话,还望纠错。