2020.9.25 第11节 指针终结篇
一、函数指针
函数指针: 指向函数的指针
1.定义一个函数指针?
方法: 用(*指针名)替换函数名,剩下东西照着函数原型写即可
2. 函数指针的赋值
用函数名赋值 两种
3.函数指针如何调用函数
3.1 只用指针名替换函数名
3.2 *指针名替换函数名
4.函数指针使用
4.1 一般都是充当函数参数使用—>回调函数
#include <stdio.h>
int max(int a, int b)
{
return a > b ? a : b;
}
int maxC(int a, char b)
{
return a > b ? a : b;
}
int Min(int a, int b)
{
return a > b ? b : a;
}
int sum(int a, int b)
{
return a + b;
}
void printNum(int a, int b)
{
printf("%d", a + b);
}
void print(int (*pF)(int, int), int a, int b)
{
printf("%d\n", pF(a, b));
}
int main()
{
int (*pFunction)(int a, int b) = NULL;
pFunction = max;
printf("%d\n", pFunction(1, 2));
printf("%d\n", (*pFunction)(1, 2));
int (*pFun)(int , int ) = NULL;
pFun = &max;
printf("%d\n", (*pFun)(1, 2));
printf("%d\n", pFun(1, 2));
print(max, 1, 2);
print(sum, 1, 2);
print(Min, 1, 2);
return 0;
}
二、typedef与函数指针
1.方法: 用(*指针名)替换函数名,剩下东西照着函数原型写即可
2.函数指针可以用typedef简化代码
#include <stdio.h>
int max(int a, int b)
{
return a > b ? a : b;
}
void printA(int (*pF)(int, int), int a, int b)
{
printf("%d\n", pF(a, b));
}
typedef int (*pF)(int, int);
void printB(pF max, int a, int b)
{
printf("%d\n", max(a, b));
}
typedef void (*pFF)(int(*)(int, int));
void printC(pFF printF, pF max, int a, int b)
{
printF(max, a, b);
}
void printAA(void (*pFF)(int(*)(int, int)), int (*pF)(int, int),int a, int b)
{
pFF(pF, a, b);
}
int main()
{
typedef int 整数;
int iNum = 1;
整数 iNumber = 2;
typedef char STR[10];
STR str;
gets_s(str, 10);
puts(str);
void (*ppp)(int (*)(int, int), int, int) = NULL;
typedef void (*YYKK)(int (*)(int, int), int, int);
YYKK pYk = NULL;
typedef int INT[2];
INT array[2];
return 0;
}
三、const与函数指针
#include <stdio.h>
void print(const char* fileName)
{
printf("%s", fileName);
}
void printA(const int a)
{
printf("%d\n", a);
}
int main()
{
const int* p1 = NULL;
int const* p2 = NULL;
const int cNum = 0;
int iNumber = 1;
p1 = &cNum;
p2 = &iNumber;
print("fileName");
int* const p3 = &iNumber;
iNumber = 1001;
printf("p3=%d\n", *p3);
const int* const p4 = NULL;
return 0;
}
四、万能函数充当函数指针
万能指针充当函数指针:
1.必须强制类型
2.必须采用*指针名的调用方式
#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
void print()
{
printf("ILoveyou\n");
}
int main()
{
void* pVoid = sum;
printf("%d\n", ((int(*)(int,int))pVoid)(1, 2));
typedef int(*PP)(int, int);
printf("%d\n", ((PP)pVoid)(1, 2));
void* p = print;
(*(void(*)())p)();
return 0;
}
五、复杂的指针
如何识别复杂的指针
右左法则?
如何识别复杂的指针
右左法则?
1.找标符符 Fun
2.往右找)
3.往左找(
4.(*fun)
int (*fun)(int *)
指向指针函数的数组指针
int (*(*fun)(int *))[5]
int (*fun)(int *,int (*)(int *))
int(*(*pfun())())()
int (*fun)(int *,int (*)(int *))
#include <stdio.h>
int print(int* p)
{
printf("%d", *p);
return *p;
}
int printA(int(*p)(int array[], int), int a, int b)
{
}
int main()
{
int num = 100l;
print(&num);
void (*pp)(int(*)(int[], int), int, int) = printA;
return 0;
}
六、多文件
一个.c文件对应一个.h文件 避免因头文件嵌套包含导致重定义问题