int Add(int a, int b) {
return a + b;
}
int main() {
int arr[2][3] = {{1, 2, 3},
{4, 5, 6}};
int (*pArr)[2][3] = &arr;
printf("%p\n", arr);
printf("%p\n", pArr);
printf("============\n");
printf("address of func Add &Add= %p\n", &Add);
printf("address of func Add Add= %p\n", Add);
int (*pAdd) (int,int) = &Add;
printf("address of func Add pAdd = %p\n", pAdd);
printf("============\n");
int res = (*pAdd)(1,2);
printf("res = %d\n", res);
return 0;
}
运行结果:
int Add(int a, int b) {
return a + b;
}
形如这样的函数Add的函数指针定义,和数组指针很像先写(*p),前边加 返回类型,后边加参数类型,便得到
int (*p)(int,int) = Add;
这就是函数指针
骚题
《c陷阱与缺陷》
typedef void(*pf)(int);
int main() {
(*(void(*)())0)();
void( *signal(int, void(*)(int)) )(int);
pf signal2(int, pf);
return 0;
}
函数指针用法:
#include <stdio.h>
int Add(int x, int y) {
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;
}
void operate(int (*pf)(int, int)) {
int x = 0, y = 0;
printf("input x,y:\n");
scanf("%d,%d", &x, &y);
printf("res = %d\n", (*pf)(x, y));
}
#define CASE break;case
int main() {
int loop = 1;
int choice = -1;
while(loop){
printf("1: add, 2:sub, 3: mul, 4:div 5:quit\n");
printf("welcome, input your choice:\n");
scanf("%d", &choice);
switch (choice) {
case 1:
operate(Add);
CASE 2:
operate(Sub);
CASE 3:
operate(Mul);
CASE 4:
operate(Div);
CASE 5:
loop = 0;
break;
}
}
return 0;
}
运行结果:
函数指针数组
int Add(int x, int y) {
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;
}
int main() {
int (*pf1)(int, int) = Add;
int (*pf2)(int, int) = Sub;
int (*pf3)(int, int) = Mul;
int (*pf4)(int, int) = Div;
int (*arr[4])(int, int) = {pf1, pf2, pf3, pf4};
int res = arr[1](1, 2);
printf("res = %d\n", res);
res = arr[3](10, 2);
printf("res = %d\n", res);
return 0;
}
运行结果:
重写例子:
#include <stdio.h>
int Add(int x, int y) {
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;
}
int main() {
int loop = 1;
int choice = -1;
int (*pfArr[5])(int, int) = {0, Add, Sub, Mul, Div};
while(loop){
printf("1: add, 2:sub, 3: mul, 4:div 0:quit\n");
printf("welcome, input your choice:\n");
scanf("%d", &choice);
if(choice == 0){
printf("quit...");
loop = 0;
} else if(choice >= 1 && choice <= 4){
int x = 0, y = 0;
printf("input x,y:\n");
scanf("%d,%d", &x, &y);
printf("res = %d\n", pfArr[choice](x,y));
}
}
return 0;
}
指向函数指针数组的指针
int (*pfArr[5])(int, int) = {0, Add, Sub, Mul, Div};
int (*(*ppfArr)[5])(int, int) = &pfArr;