C语言进阶课程学习记录-第36课 - 函数与指针分析
- 函数类型
- 实验-函数指针
- 实验-回调机制
- 小结
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
函数类型
实验-函数指针
#include <stdio.h>
typedef int(FUNC)(int);
int test(int i)
{
return i * i;
}
void f()
{
printf("Call f()...\n");
}
int main()
{
FUNC* pt = test;
//void(*pf)() = &f;
void(*pf)() = (int *)0x00401340;//ok
printf("pf = %p\n", pf);
printf("f = %p\n", f);
printf("&f = %p\n", &f);
pf();
(*pf)();
printf("Function pointer call: %d\n", pt(2));
return 0;
}
/*
output:
pf = 00401340
f = 00401340
&f = 00401340
Call f()...
Call f()...
Function pointer call: 4
*/
实验-回调机制
#include <stdio.h>
typedef int(*Weapon)(int);
void fight(Weapon wp, int arg)
{
int result = 0;
printf("Fight boss!\n");
result = wp(arg);
printf("Boss loss: %d\n", result);
}
int knife(int n)
{
int ret = 0;
int i = 0;
for(i=0; i<n; i++)
{
printf("Knife attack: %d\n", 1);
ret++;
}
return ret;
}
int sword(int n)
{
int ret = 0;
int i = 0;
for(i=0; i<n; i++)
{
printf("Sword attack: %d\n", 5);
ret += 5;
}
return ret;
}
int gun(int n)
{
int ret = 0;
int i = 0;
for(i=0; i<n; i++)
{
printf("Gun attack: %d\n", 10);
ret += 10;
}
return ret;
}
int main()
{
fight(knife, 3);
fight(sword, 4);
fight(gun, 5);
return 0;
}
/*
output:
Fight boss!
Knife attack: 1
Knife attack: 1
Knife attack: 1
Boss loss: 3
Fight boss!
Sword attack: 5
Sword attack: 5
Sword attack: 5
Sword attack: 5
Boss loss: 20
Fight boss!
Gun attack: 10
Gun attack: 10
Gun attack: 10
Gun attack: 10
Gun attack: 10
Boss loss: 50
*/
小结
C语言中的函数都有特定的类型
可以使用函数类型定义函数指针
函数指针是实现回调机制的关键技术
通过函数指针可以在C程序中实现固定地址跳转