C语言之做一个可供调用的函数指针表
这篇C语言之为表达式计算器实现函数调用功能中,函数表方法是按参数多少来定义函数指针,这次再研究一下函数指针,做一个更好用的函数指针表!!!
有参数的函数指针
- 定义函数hello,无返回值,一个参数
- 定义函数指针fp,无返回值,一个参数:void (fp) (char);
- 赋值:fp = hello;
- 调用:fp (“Tomson”);,相当于调用函数hello: hello(“Tomson”);
源码如下:
/* filename : ftb.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* compile: gcc ftb.c -o ftb */
/* run: ./ftb */
/* define function hello with an argument */
void
hello (char *info)
{
printf ("Hello, [%s]!\n", info);
}
/**/
int
main (int argc, char *argv[])
{
void (*fp) (char*); //define function pointer
fp = hello; //assignment hello to function pointer
fp ("Tomson"); //call function pointer equal call hello
return 0;
}
//-----procedure-----//
编译运行,顺利通过,结果如下:
gwsong@ubuntu:~/works/tscm/tt$ gcc ftb.c -o ftb
gwsong@ubuntu:~/works/tscm/tt$ ./ftb
Hello, [Tomson]!
gwsong@ubuntu:~/works/tscm/tt$
空参数列表的函数指针
- 无参数的函数指针:void (*fp) (void);,用void来确定无参数!!!
- 空参数列表的函数指针:void (*fp) ();,用空列表来表示参数量不确定!!!
- 以上两者区别很大,也很明显,但很容易被忽略!!!
- 简单测试空参数列表的函数指针,函数hi无参数,函数ha一个参数,函数ho两个参数!
- 定义void (*fp)(),分别将上面定义的三个函数赋值给fp,看一下运行结果,编码如下:
/* filename: ftc.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* compile: gcc ftc.c -o ftc */
/* run: ./ftc */
/* no arg */
void hi (void)
{
printf ("Hi!\n");
}
/* one arg */
void ha (char *info)
{
printf ("Ha! %s\n", info);
}
/* two args */
void ho (char *s, int a)
{
printf ("Ho! %s, [%d]\n", s, a);
}
/* test function */
void
test_func