不知道你有没想过代码能不能像参数一样传递?
如果在程序中定义了一个函数,那么在编译时系统就会为这个函数代码分配一段存储空间,这段存储空间的首地址称为这个函数的地址。而且函数名表示的就是这个地址。既然是地址我们就可以定义一个指针变量来存放,这个指针变量就叫作函数指针变量,简称函数指针。
演示一下函数指针的基本用法
#include int Max(int { return } int main() { int(*pMax)(int, int); pMax = Max; int c = pMax(3,5); printf(“%d\n”,c); return 0; } |
下面的例子实现把函数当做参数传递的功能
#include int Max(int { return } int Add(int { return } int Func(int(*pF)(int, int),int { return } int main() { int c = Func(Max, 3, 5); printf(“%d\n”,c); int d = Func(Add, 3, 5); printf(“%d\n”, d); return 0; } |
2021年12月16日
22时15分