C语言函数如何作为参数传递

紫回蓝 2011-07-26 04:20:47
在学习数据结构链表中,其中有一个LocalElem();函数
其中传递的函数是compare();
当然函数compare是抽象的,具体的可以是相等什么的
我根据理解,写下函数的声明

int LocalElem(compare(),*e);
用e来存储第一个满足compare()的函数

希望大家给我个例子,再加些理论,谢谢。非常感谢
...全文
801 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
懒得打字 2011-07-27
  • 打赏
  • 举报
回复
写错了
typedef int (*COMPARE)()
懒得打字 2011-07-27
  • 打赏
  • 举报
回复
……
好吧,先typedef函数指针,当然不这么干也行,就是代码难读一点
typedef int *COMPARE()

函数声明是:
int LocalElem(COMPARE c,int *e);

假设函数是int compare();调用方法是:
int LocalElem(compare, e);
沭水河畔 2011-07-26
  • 打赏
  • 举报
回复

#include <stdio.h>

int add(int a,int b)
{
return a+b;
}

int sub(int a,int b)
{
return a-b;
}

int (*fun)(int a,int b);

int calc(int a,int b,int (*fun)(int a,int b))
{
return fun(a,b);
}

int main(void)
{
int num1,num2;
char op;
scanf("%d %d %c",&num1,&num2,&op);

switch(op)
{
case '+':
fun=add;
break;
case '-':
fun=sub;
break;
default:
fun=add;
}

printf("%d\n",calc(num1,num2,fun));

return 0;
}
赵4老师 2011-07-26
  • 打赏
  • 举报
回复
Example

/* QSORT.C: This program reads the command-line
* parameters and uses qsort to sort them. It
* then displays the sorted arguments.
*/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int compare( const void *arg1, const void *arg2 );

void main( int argc, char **argv )
{
int i;
/* Eliminate argv[0] from sort: */
argv++;
argc--;

/* Sort remaining args using Quicksort algorithm: */
qsort( (void *)argv, (size_t)argc, sizeof( char * ), compare );

/* Output sorted list: */
for( i = 0; i < argc; ++i )
printf( "%s ", argv[i] );
printf( "\n" );
}

int compare( const void *arg1, const void *arg2 )
{
/* Compare all of both strings: */
return _stricmp( * ( char** ) arg1, * ( char** ) arg2 );
}


Output

[C:\code]qsort every good boy deserves favor
boy deserves every favor good


至善者善之敌 2011-07-26
  • 打赏
  • 举报
回复
你们抢的太凶了
ryfdizuo 2011-07-26
  • 打赏
  • 举报
回复
google 函数指针
jackyjkchen 2011-07-26
  • 打赏
  • 举报
回复
函数指针的干活,传函数名
bdmh 2011-07-26
  • 打赏
  • 举报
回复
传递函数指针
  • 打赏
  • 举报
回复
搜索 C语言 函数指针

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧