函数指针
- 函数名本质是一个函数指针
- 可以利用函数指针调用函数
函数指针的定义方式
- 先定义函数类型,再通过类型定义函数指针
- 定义函数指针类型,通过类型定义函数指针
- 直接定义函数指针变量
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void func0401(int a, char c) {
printf("hello world\n");
}
void test0401() {
//先定义函数类型,再通过类型定义函数指针
typedef void(func)(int, char);
func* pFunc = func0401;
pFunc(1, 'a');
//定义函数指针类型,通过类型定义函数指针
typedef void(*pfunc)(int, char);
pfunc pFunc1 = func0401;
pFunc1(1, 'a');
//直接定义函数指针变量
void(*p)(int, char)= func0401;
p(1, 'a');
}
int main(void)
{
test0401();
return 0;
}
函数指针和指针函数的区别
函数指针:指向函数的指针
指针函数:函数返回值是指针的函数
函数指针的数组
void func0402() {
printf("func0402调用了\n");
}
void func0403() {
printf("func0403调用了\n");
}
void func0404() {
printf("func0404调用了\n");
}
void test0402() {
//函数指针的数组
void(*pArray[3])();
pArray[0] = func0402;
pArray[1] = func0403;
pArray[2] = func0404;
for (size_t i = 0; i < 3; i++)
{
pArray[i]();
}
}
函数指针的应用:回调函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//打印函数:可以打印任意类型的数据
void printText(void* data,void(*myPrint)(void*)) {
myPrint(data);
}
void myPrintInt(void* data) {
printf("%d\n", *(int*)data);
}
void test0501() {
int a = 10;
printText(&a, myPrintInt);
}
int main(void)
{
test0501();
return 0;
}