函数指针、函数指针数组、函数指针数组指针、函数二重指针
//函数指针、函数指针数组、函数指针数组指针、函数二重指针
//只有函数指针数组,没有函数数组。
//二重指针也是普通指针,数组指针的解引用就是普通指针
//二维数组的精髓*(*(p + i) + j)精髓就是*(p + i)数组指针加减运算到指定到
//一维数组,然后解引用变为普通指针。
#include <stdio.h>
//*******总是忘记,typedef之后是一个类型不是变量,记得初始化变量********
//函数二重指针(指向函数指针数组的首元素首地址)
typedef int (*(*P2))(int,int);
//函数指针数组指针(指向整个函数指针数组,解引用为普通指针,即为函数二重指针)
typedef int (*(*P3)[])(int,int);
int add(int,int);
int sub(int,int);
int main()
{
//【1】函数指针的用法,指向函数,也可为&函数名。
int (*p4)(int,int) = add;
int (*p5)(int,int) = sub;
//【2】函数指针数组的用法
int (*p1[])(int,int) = {p4, p5};
//int (*p1[])() = {add,sub}; //可以不写形参,甚至可以包含形参
//格式不一样的,中括号的数字初始化的时候可写可不写
//int (*p1[])(int,int) = {&add,&sub};
//用法
//p1[0](1,2);
//(*p1)(1,2);
printf("%d.\n",p1[0](1,2));
printf("%d.\n",(*p1)(1,2));
//p1[1](3,2);
//(*(p1+1))(3,2);
printf("%d.\n",p1[1](3,2));
printf("%d.\n",(*(p1+1))(3,2));
//【3】函数二重指针用法;(作为普通指针指向->函数指针数组的首元素的首地址)
P2 p2 = p1;
//p2 = &p1[0]
//用法
printf("\n");
//(*p2)(1,2);
//p2[0](1,2);
printf("%d.\n",(*p2)(1,2));
printf("%d.\n",p2[0](1,2));
//(*(p2+1))(3,2);
//p2[1](3,2);
printf("%d.\n",(*(p2+1))(3,2));
printf("%d.\n",p2[1](3,2));
//【4】函数指针数组指针(指向整个函数指针数组,解引用为普通指针)
P3 p3 = &p1;
//用法
printf("\n");
//(*p3)[0](1,2);
//(*(*p3))(1,2);
printf("%d.\n",(*p3)[0](1,2));
printf("%d.\n",(*(*p3))(1,2));
//(*p3)[1](3,2);
//(*(*p3+1))(3,2);
printf("%d.\n",(*p3)[1](3,2));
printf("%d.\n",(*(*p3+1))(3,2));
//【3】和【4】的关系,数组指针解引用为普通指针
p2 = *p3;
//p2 = (P2)p3;
//用法如上,测试一下对错
printf("\n");
//(*p2)(1,2);
//p2[0](1,2);
printf("%d.\n",(*p2)(1,2));
printf("%d.\n",p2[0](1,2));
//(*(p2+1))(3,2);
//p2[1](3,2);
printf("%d.\n",(*(p2+1))(3,2));
printf("%d.\n",p2[1](3,2));
return 0;
}
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
运行结果
gcc -o test test.c
./test