标签:style blog io ar color sp div log bs
简单的介绍下C语言函数指针的用法。
函数指针的声明:
char (* FunPtr)(char); 或者char (* FunPtr)(char ch); (声明类型个形参类型根据实际情况更改)
例:
1 #include"stdio.h" 2 3 char myFun(char ch) 4 { 5 printf("myFun is called, your char is %c.\n",ch); 6 return ‘w‘; 7 } 8 9 void main() 10 { 11 char temp; 12 13 char (* funPtr)(char); //定义一个函数指针 14 funPtr=myFun; //将myFun的地址给funPtr 15 temp=funPtr(‘s‘); //此时可以认为对funPtr的调用就等同于对myFun的调用 16 17 printf("return value: %c\n",temp); 18 printf("size of myFun: %d\n",sizeof(funPtr)); 19 }
结果:
myFun is called, your char is s.
return value: w
size of myFun: 4
也可以将函数的定义放到结构体中,通过结构体成员变量来调用。
例:
1 #include"stdio.h" 2 3 typedef struct{ 4 char (* funPtr)(char); //定义一个函数指针 5 }myFunStruct_t; 6 7 char myFun(char ch) 8 { 9 printf("myFun is called, your char is %c.\n",ch); 10 return ‘w‘; 11 } 12 13 void main() 14 { 15 char temp; 16 17 myFunStruct_t myFunStruct; 18 myFunStruct.funPtr=myFun; //将myFun的地址给funPtr 19 temp=myFunStruct.funPtr(‘s‘); //此时可以认为对funPtr的调用就等同于对myFun的调用 20 21 printf("return value: %c\n",temp); 22 printf("size of myFunStruct_t: %d\n",sizeof(myFunStruct_t)); 23 }
结果:
myFun is called, your char is s.
return value: w
size of myFunStruct_t: 4
或者来点更高级的玩法,
例:
1 #include"stdio.h" 2 3 typedef void (* funInPtr_t)(void); //函数原型定义 4 typedef void (* funOutPtr_t)(void); 5 6 typedef struct{ 7 funInPtr_t funInPtr; 8 }myInStruct_t; 9 10 typedef struct{ 11 funOutPtr_t funOutPtr; 12 myInStruct_t myInStruct; 13 }myOutStruct_t; 14 15 void myInFun(void) 16 { 17 printf("myInFun\n"); 18 } 19 20 void myOutFun(void) 21 { 22 printf("myOutFun\n"); 23 } 24 25 void main() 26 { 27 myOutStruct_t myOutStruct; 28 myOutStruct.funOutPtr=myOutFun; 29 myOutStruct.myInStruct.funInPtr=myInFun; 30 31 myOutStruct.funOutPtr(); //外层函数 32 myOutStruct.myInStruct.funInPtr(); //内层函数 33 34 printf("size of myInStruct_t: %d\n",sizeof(myInStruct_t)); 35 printf("size of myOutStruct_t: %d\n",sizeof(myOutStruct_t)); 36 }
结果:
myOutFun
myInFun
size of myInStruct_t: 4
size of myOutStruct_t: 8
是不是像某些语言里的“一点到底”?
C语言的指针就是这么任性!
标签:style blog io ar color sp div log bs
原文地址:http://www.cnblogs.com/cntsw/p/4149298.html