函数指针合集
学习目标:
- 认识函数指针
- typedef和函数指针
- 万能指针充当函数指针
[TOC]
函数指针合集
概念
什么是函数指针
对应函数在内存当中的首地址
定义函数指针
使用(*标识符(可以当作指针变量的名字))替换函数名,剩下的照抄
使用示例
1
2
3
4
5
6int func(int a,int b)
{
;
}
int (*p_func)(int a,int b)//函数指针
void (*p)(int ,int )=NULL;//形参可以不写
通过函数指针调用
给函数指针赋值(通常使用函数名)
直接用函数指针替换函数名调用
指针的
*
操作,调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23void func1(int a,int b)
{
printf("%d,%d\n",a,b);
}
void *p_func2 ()
{
printf("void (*p_func2) (int a,int b)\n");
}
int main()
{
//在main里面的定义的函数指针
void (*p)(int a,int b)=NULL;
void *pp=p_func2();
p=func1;
func1(2,5);
//在外面定义的函数指针
*p_func2();
*pp;
system("pause");
return 0;
}
函数指针有什么用?、
充当回调函数(以函数指针为参数的函数)
实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31#include<stdio.h>
#include <stdlib.h>
int Max(int a, int b)
{
return a>b?a:b;
}
int Min(int a,int b)
{
if(a>b)
return b;
return a;
}
void Printf_S(int (*p)(int ,int),int a,int b)
{
printf("%d\n",p(a,b));
}
void func()
{
void (*pp)(int (int ,int),int ,int )=Printf_S;
pp(Min,2,3);
pp(Max,2,3);
}
int main()
{
func();
return 0;
}运行结果:
typedef和函数指针
typedef
基本用法,给类型起别名定义函数指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#include<stdio.h>
#include <stdlib.h>
int Max(int a, int b)
{
return a>b?a:b;
}
int Min(int a,int b)
{
if(a>b)
return b;
return a;
}
void Printf_S(int (*p)(int ,int),int a,int b)
{
printf("%d\n",p(a,b));
}
int main()
{
void (*pp)(int (*)(int ,int),int ,int )=Printf_S;
typedef void (*ppp)(int (*)(int ,int),int ,int );
ppp p_f=Printf_S;
p_f(Max,3,5);
pp(Min,3,5);
return 0;
}
万能指针充当函数指针
万能指针:空类型的指针(
void *p
)万能指针可以操作任何类型的指针,但是在使用前必须强制类型转换
- 语法:(要转换的类型)
万能指针操作数据类型
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
int a=244;
float b=3.14f;
void *p=NULL;
p=&a;
printf("%d\n",*(int *)p);
p=&b;
printf("%f\n",*(float *)p);
return 0;
}函数指针的类型(去掉变量名)
例如:
void (*p)(int,int);
类型为void (*)(int,int)
调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14int main()
{
int a=244;
float b=3.14f;
void *p=NULL;
p=&a;
printf("%d\n",*(int *)p);
p=&b;
printf("%f\n",*(float *)p);
p=print;
((void(*)())p)();
(*(void(*)())p)();
return 0;
}
常见问题
- 区分下面4中代码
1 |
|
*
前面的const
写在前面和后面是一样的例如:
const *int x=1;
int const* x=1;
都是让指向的值变成常量作用是修饰数据类型的,也就是指向指针所指向的类型
int* const p
是指针变成了常量,指针只能指一个地址
区分指针数组,数组指针(哪个在后面就是什么)
指针数组
1
2
3
4
5
6
7
8int main()
{
char* p[3]={"chg","zjy","tsy"};
for (int i = 0; i < 3; ++i) {
puts(p[i]);
}
return 0;
}
函数指针合集
https://tsy244.github.io/2023/04/20/C/函数指针合集/