c语言回调函数结构体参数传递,C语言中的回调函数 - Dake的信息摘录博客 - OSCHINA - 中文开源技术交流社区...

回调函数是一个程序员不能显式调用的函数;通过将回调函数的地址传给调用者从而实现调用。回调函数使用是必要的,在我们想通过一个统一接口实现不同 的内 容,这时用回掉函数非常合适。比如,我们为几个不同的设备分别写了不同的显示函数:void TVshow(); void ComputerShow(); void NoteBookShow()...等等。这是我们想用一个统一的显示函数,我们这时就可以用回掉函数了。void show(void (*ptr)()); 使用时根据所传入的参数不同而调用不同的回调函数。

不同的编程语言可能有不同的语法,下面举一个c语言中回调函数的例子,其中一个回调函数不带参数,另一个回调函数带参数。

例子1:

//Test.c

#include

#include

int Test1()

{

int i;

for (i=0; i<30; i++)

{

printf("The %d th charactor is: %c/n" , i, ( char )( 'a' + i%26));

}

return 0;

}

int Test2( int num)

{

int i;

for (i=0; i

{

printf("The %d th charactor is: %c/n" , i, ( char )( 'a' + i%26));

}

return 0;

}

/**

* 指向函数的指针作函数参数

*/

void Caller1( void (*ptr)())

{

(*ptr)();

}

/**

* 指向函数的指针作函数参数

* 这里第一个参数是为指向函数的指针服务的,

* 不能写成void Caller2(int (*ptr)(int n)),这样的定义语法错误。

*/

void Caller2( int n, int (*ptr)())

{

(*ptr)(n);

return ;

}

int main()

{

printf("************************/n" );

Caller1(Test1); //相当于调用Test2();

printf("&&&&&&************************/n" );

Caller2(30, Test2); //相当于调用Test2(30);

return 0;

}

//Test.c

#include

#include

int Test1()

{

int i;

for (i=0; i<30; i++)

{

printf("The %d th charactor is: %c/n", i, (char)('a' + i%26));

}

return 0;

}

int Test2(int num)

{

int i;

for (i=0; i

{

printf("The %d th charactor is: %c/n", i, (char)('a' + i%26));

}

return 0;

}

/**

* 指向函数的指针作函数参数

*/

void Caller1(void (*ptr)())

{

(*ptr)();

}

/**

* 指向函数的指针作函数参数

* 这里第一个参数是为指向函数的指针服务的,

* 不能写成void Caller2(int (*ptr)(int n)),这样的定义语法错误。

*/

void Caller2(int n, int (*ptr)())

{

(*ptr)(n);

return;

}

int main()

{

printf("************************/n");

Caller1(Test1); //相当于调用Test2();

printf("&&&&&&************************/n");

Caller2(30, Test2); //相当于调用Test2(30);

return 0;

}

以上通过将回调函数的地址传给调用者从而实现调用,但是需要注意的是带参回调函数的用法。要实现回调,必须首先定义函数指针。函数指针的定义这里稍微提一下。比如:

int (*ptr)();

这里ptr是一个函数指针,其中(*ptr)的括号不能省略,因为括号的优先级高于星号,那样就成了一个返回类型为整型的函数声明了.

转自:http://my.oschina.net/jayzonex/blog/9939

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值