今天写代码,写着写着就用到函数指针数组,通过按键的ID和函数指针数据执行按键要做的事情。水平不够,所以这玩意不经常用,突然用到都忘记怎么用。所以回顾了下学习使用了下函数指针、函数指针数组。
函数指针
1、定义函数指针
void (*fun_pointer)(char);
2、函数指针赋值与调用
fun_pointer = print_a;
(*fun_pointer)('a');
要赋值给函数指针的函数的原型一定要和定义的函数指针一致。
示例:
#include "stdio.h"
void print_a(char arg)
{
printf("%c\r\n",arg);
}
void (*fun_pointer)(char); //定义函数指针
int main(int argc,char **argv)
{
fun_pointer = print_a;
(*fun_pointer)('a');
return 0;
}
更常用的用法应该是下面这样的:
#include "stdio.h"
typedef void (*fun_pointer)(char); //定义个这样的函数指针类型,与typedef a[10]用法类似
void print_a(char arg)
{
printf("%c\r\n",arg);
}
int main(int argc,char **argv)
{
fun_pointer pfun = print_a; //定义一个函数指针并赋值
(*pfun)('a'); //调用函数
return 0;
}
函数指针数组
定义函数指针数组
void (*fun_pointer[FUN_POINTER_ARR_SIZE])(char);
可以指定大小,也可以不指定大小,和数组定义法差不多。
示例:
#include "stdio.h"
#include "stdlib.h"
#define FUN_POINTER_ARR_SIZE 3
typedef void (*fun_pointer[FUN_POINTER_ARR_SIZE])(char);
void print_a(char arg)
{
printf("arg = %c\r\n",arg);
}
void print_d(char c)
{
printf("c = %d\r\n",c);
}
void print_x(char arg)
{
printf("arg = %x\r\n",arg);
}
fun_pointer pfun[4] = {print_a,print_d,print_x};
int main(int argc,char **argv)
{
int input;
scanf("%d",&input);
if(input == 0)
{
(*pfun)[0]('a');
}
else if(input == 1)
{
(*pfun)[1]('c');
}
else if(input == 2)
{
(*pfun)[1]('b');
}
return 0;
}
typedef void (*fun_pointer[FUN_POINTER_ARR_SIZE])(char);
使用typedef
来进行操作的话FUN_POINTER_ARR_SIZE 大小要指定,不然就报错
fun_pointer pfun[4]
可以指定大小,也可以不用,大小不一定要和FUN_POINTER_ARR_SIZE
相等