函数指针的一个用法出现在菜单驱动系统中。例如程序可以提示用户输入一个整数值来选择菜单中的一个选项。用户的选择可以做函数指针数组的下标,而数组中的指针可以用来调用函数。
//函数指针数组的使用 #include <stdio.h> void func0(int i) { printf("your enter %d so func%d is called ",i,i); } void func1(int i) { printf("your enter %d so func%d is called ",i,i); } void func2(int i) { printf("your enter %d so func%d is called ",i,i); } void func3(int i) { printf("your enter %d so func%d is called ",i,i); } //输入哪个就调哪个函数 int main(void) { void (*fpa[4])(int) = {func0,func1,func2,func3}; #if 0 //虽然在这里的switch可有可无,但是以后在项目中不可能用数字代替的,一般是一个单词,或者点击一下窗口中的某一点,然后通过switch来执行相应的函数。 int choice; while(1) { printf("pls input number between o and 3:"); scanf("%d",&choice); switch(choice) { case 0: fpa[choice](choice);break; case 1: fpa[choice](choice);break; case 2: fpa[choice](choice);break; case 3: fpa[choice](choice);break; default: return 0; } } #endif #if 0 //不使用switch int choice; while(1) { printf("pls input number between o and 3:"); scanf("%d",&choice); fpa[choice](choice); // (*fpa[choice])(choice);//这样使用也对,不推荐这样用 } #endif #if 0 //把访问函数指针数组里的元素由上面的数组下标访问形式 改为 指针形式访问 ,需要注意 int choice; while(1) { printf("pls input number between o and 3:"); scanf("%d",&choice); (*(fpa+choice))(choice);//正确 // (*fpa)(choice);//错误 // (*(*(fpa+choice)))(choice);//这样使用也对,不推荐这样用 } #endif return 0; }