函数指针:一个指针,指向的内存是函数。
- 目录
- 普通函数指针的定义与使用
- 两个较为特殊的实例
- 指向函数的指针数组
- 指向函数的指针数组的行指针。
一:普通函数指针的定义与使用
#include<stdio.h> char* function(const char *t1,const char *t2) { //执行函数功能代码。。。 //返回字符指针 } int main() { char * (*func)(char *t1,char *t2); func=&function;//或者func=function直接赋值 func("hello","world"); return 0; }
程序分析:主函数中定义了一个func的函数指针,该指针指向了一个传入参数为两个char*的变量,返回值为char*的函数。通过函数指针调用函数
二:两个实例的分析
#include<stdio.h> int function() { //函数功能实现代码。。。 //返回值为int } int main() { void (*p)(); *(int*)&p=(int)function;
(*p)(); return 0; }
程序分析:定义了一个函数指针p,p指向没有参数和返回值的函数。将function函数地址转换成int类型数据赋值给强制性转换成int*型的p。通过p调用函数。
(*(void(*) ())0)();
代码分析:将0转换成指向无参,无返回值的函数指针,取0地址内存的内容,然后调用函数。
三:函数指针数组的使用
#include<stdio.h> char* function1(char* temp) { printf("%s",temp); } char* function2(char* temp) { printf("%s",temp); } char* function3(char* temp) { printf("%s",temp); } int main() { char* (*p[3])(char* temp); p[0]=function1; p[1]=function2; p[2]=function3; p[0]("func1"); p[1]("func2"); p[2]("func3"); return 0; }
程序分析:定义了一个指向参数为char*,并且返回值类型为char*的函数指针数组。通过数组元素调用函数。
四:函数指针数组指针的使用
#include<stdio.h> #include<string.h> char* function1(const char* temp) { printf("%s",temp); return (char*)0; } char* function2(const char* temp) { printf("%s",temp); return (char*)0; } char* function3(const char* temp) { printf("%s",temp); return (char*)0; } int main() { //定义一个函数指针数组。 char* (*p[3])(const char*); //定义一个指向函数指针数组的行指针 char* (*(*pa)[3])(const char*p); pa=&p; p[0][0]=&function1; p[0][1]=&function2; p[0][1]=&function3; pa[0][0]("func1"); pa[0][1]("func2"); pa[0][2]("func3"); return 0; }
程序分析:定义了一个函数指针数组,又定义了一个指向函数指针数组的行指针,通过行指针调用函数。