typedef 函数指针

“函数指针”的本质是一个指针变量,只不过该指针变量指向函数。

1:简单应用

形式1:返回类型(*函数名)(参数表)

  1. #include <stdio.h>  
  2.   
  3. char* (*test)(char *);//定义一个函数指针,使用之前对其赋值  
  4. char* fun(char *ch)//定义一个普通函数  
  5. {   
  6.     return ch;  
  7. }  
  8.   
  9. void main()  
  10. {  
  11.     test = fun;//对函数指针赋值  
  12.     printf("%s\n",test("hello world"));  
  13. }  
#include <stdio.h>

char* (*test)(char *);//定义一个函数指针,使用之前对其赋值
char* fun(char *ch)//定义一个普通函数
{ 
	return ch;
}

void main()
{
	test = fun;//对函数指针赋值
	printf("%s\n",test("hello world"));
}

2:结合typedef 应用函数指针

形式2:typedef 返回类型(*函数名)(参数表)

  1. #include <stdio.h>  
  2.   
  3. typedef char* (*TEST)(char *);//使用typedef定义一个函数指针类型  
  4. TEST test;//定义函数指针  
  5.   
  6. char* fun(char *ch)//定义一个普通函数  
  7. {   
  8.     return ch;  
  9. }  
  10.   
  11. void main()  
  12. {  
  13.     test = fun;//对函数指针赋值  
  14.     printf("%s\n",test("hello world"));  
  15. }  
#include <stdio.h>

typedef char* (*TEST)(char *);//使用typedef定义一个函数指针类型
TEST test;//定义函数指针

char* fun(char *ch)//定义一个普通函数
{ 
	return ch;
}

void main()
{
	test = fun;//对函数指针赋值
	printf("%s\n",test("hello world"));
}
typedef的功能是定义新的类型。

第一句就是定义了一种TEST类型的函数指针。该函数返回类型为char * ,参数类型为char * 。在下面的代码中可以像int,char一样使用TEST类型了。

第二句利用TEST类型定义来一个变量test可以像平常一样使用了。

相比第一种方法,此方法较直观


3:结合typedef 应用函数指针数组

形式3:typedef 返回类型(*函数名[ ])(参数表)

  1. #include <stdio.h>  
  2.   
  3. char* fun1(char *ch)//定义一个普通函数  
  4. {   
  5.     return ch;  
  6. }  
  7.   
  8. char* fun2(char *ch)//定义一个普通函数  
  9. {   
  10.     return ch;  
  11. }  
  12.   
  13.   
  14. void main()  
  15. {  
  16.     typedef char* (*TEST[2])(char *);//使用typedef定义一个函数指针类型  
  17.     TEST test = {fun1,fun2};  
  18.   
  19.     printf("1:%s\n 2:%s \n",test[0]("call fun1"),test[0]("call fun2") );  
  20. }  
#include <stdio.h>

char* fun1(char *ch)//定义一个普通函数
{ 
	return ch;
}

char* fun2(char *ch)//定义一个普通函数
{ 
	return ch;
}


void main()
{
	typedef char* (*TEST[2])(char *);//使用typedef定义一个函数指针类型
	TEST test = {fun1,fun2};

	printf("1:%s\n 2:%s \n",test[0]("call fun1"),test[0]("call fun2") );
}
相比第一种方法,此方法更为直观
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值