# 一、引例

``````#include<stdio.h>
int sum(int x,int y)
{
return x+y;
}
int main()
{
int(*p)(int,int)=&sum;
printf("%dn",p(2,3));
return 0;
}
``````

（存放函数的地址

# 二、函数指针

### 函数的地址

``````	printf("%pn",&sum);
``````

``````	printf("%pn",&sum);
printf("%pn",sum);
``````

### 函数指针的写法

``````int* p(int int)=sum;
``````

``````int (*P)(int,int)=sum;
``````

``````int (*P)(int x,int y)=sum;
``````

### 函数指针的调用

``````printf("%dn",(*p)(2,3));
``````

``````	printf("%dn", (p)(2, 3));
printf("%dn", (*p)(2, 3));
printf("%dn", (**p)(2, 3));
printf("%dn", (***p)(2, 3));
``````

``````	printf("%dn", p(2, 3));
printf("%dn", sum(2, 3));
``````

``````	printf("%dn",*p(2, 3));
``````

p(2,3)先结合，已经返回了int类型的值，不可再解引用！！

# 三、函数指针数组

``````#include<stdio.h>
{
return x + y;
}
int sub(int x, int y)
{
return x - y;
}
int mul(int x, int y)
{
return x * y;
}
int main()
{
int(*parr[3])(int x, int y) = { add,sub,mul };
int i = 0;
for (i = 0; i < 3; i++)
{
printf("%dn", parr[i](2, 3));
}
return 0;
}
``````

### 函数指针数组的写法

``````int(*parr[3])(int x, int y) = { add,sub,mul };
``````

parr首先与[3]结合变成一个数组，数组名parr，元素个数3

### 函数指针数组的应用—小型计算器

``````#include<stdio.h>
{
return x + y;
}

int Sub(int x, int y)
{
return x - y;
}

int Mul(int x, int y)
{
return x * y;
}

int Div(int x, int y)
{
return x / y;
}

{
printf("**************************n");
printf("**** 1. add    2. sub ****n");
printf("**** 3. mul    4. div ****n");
printf("****     0. exit      ****n");
printf("**************************n");
}

int main()
{
int input = 0;
do {

int x = 0;
int y = 0;
int ret = 0;
printf("请选择:>");
scanf("%d", &input);

switch (input)
{
case 1:
printf("请输入2个操作数>:");
scanf("%d %d", &x, &y);
printf("sum = %dn", ret);
break;
case 2:
printf("请输入2个操作数>:");
scanf("%d %d", &x, &y);
ret = Sub(x, y);
printf("sum = %dn", ret);
break;
case 3:
printf("请输入2个操作数>:");
scanf("%d %d", &x, &y);
ret = Mul(x, y);
printf("sum = %dn", ret);
break;
case 4:
printf("请输入2个操作数>:");
scanf("%d %d", &x, &y);
ret = Div(x, y);
printf("sum = %dn", ret);
break;
case 0:
printf("退出程序n");
break;
default:
printf("选择错误，重新选择!n");
break;
}

} while (input);
return 0;
}
``````

# 四、回调函数

``````#include<stdio.h>
{
return x + y;
}

int Sub(int x, int y)
{
return x - y;
}
int clac(int (*p)(int, int),int x,int y)
{
return p(x, y);
}
int main()
{
int x = 2, y = 3;
printf("%dn", clac(Sub, x, y));
return 0;
}
``````

``````	int x = 2, y = 3;
int (*pb)(int, int) = Sub;
printf("%dn", clac(pa, x, y));
printf("%dn", clac(pb, x, y));
``````

THE END