<style type="text/css">
<!--
p
{margin-bottom:0.21cm}
-->
</style>
有些编译器可能编译不通过,需要改为如下的形式:
另一个函数指针数组的例如:
C程序在编译时,每一个函数都有一个入口地址,该地址就是函数指针所指向的地址。有了指向函数的指针变量后,可用该指针变量调用函数,就如同用指针变量可引用其他类型变量一样,其概念上是一致的。函数指针有两个用途:调用函数和做函数的参数。
函数指针的声明方法如下:
函数类型(标志符 指针变量名)(形参列表)
注:
1)“函数类型”:说明该函数的返回类型;
2)“(标志符 指针变量名)”:该括号不能省略,说明了一个返回的数据类型是指针的函数
3)“形参列表”:表示指针变量指向的函数所带的参数列表。
举例:
int func(int x , int y) //声明一个函数
int (*f)(int x, int y) //声明一个函数指针
f = func; //将func函数的首地址赋给指针f;
赋值时函数func不带括号,也不带参数,由于func代表函数的首地址,因此经过赋值以后,指针f就指向函数func(int x, int y)的代码的首地址。
测试代码如下:
#include <stdio.h>
void test(char *str)
{
printf("%s\n", str);
}
int main()
{
void (*t)(char*);
char *s = "This is a test!\n";
t = test;
(*t)(s);
return 0;
}
有些编译器可能编译不通过,需要改为如下的形式:
#include <stdio.h>
typedef void (*t_ptr)(char*);
void test(char *str)
{
printf("%s\n", str);
}
int main()
{
// void (*t)(char*);
char *s = "This is a test!\n";
t_ptr t = test;
t(s);
return 0;
}
另一个函数指针数组的例如:
#include <stdio.h>
typedef void (*init_func)(void);
void hello1(void)
{
printf("hello 1\n");
}
void hello2(void)
{
printf("hello 2\n");
}
void hello3(void)
{
printf("hello 3\n");
}
static init_func init[] = {
hello1,
hello2,
hello3,
0,
};
int main()
{
int i;
for(i = 0; init[i]; i++)
{
init[i]();
}
return 0;
}