函数指针问题

nanjingnew4 2011-11-22 06:06:45

typedef int (*compare)(const void *x, const void *y);

int my_compare(const void *x, const void *y){
const int *a=(int *)x;
const int *b=(int *)y;
if(*a>*b)
return 1;
if(*a==*b)
return 0;
return -1;
}

// -- compare conmpareFunc是不是要求compareFunc的函数原型返回值必须是compare类型??
//也就是说my_compare这个函数返回值应该是个指针,指向另一个函数,该函数的参数是(const void *, const void *)
void my_sort(void *data, int length, int size, compare compareFunc){
char *d1,*d2;
//do something
if(compareFunc(d1,d2)<0){
//do something
}else if(compareFunc(d1,d2)==0){
//do something
}
else{
//do something
}
//do something
}

int main(int argc, char **argv){
int arr={2,4,3,656,23};
// 传递my_compare的地址
my_sort(arr, 5, sizeof(int), my_compare);
//do something
return 0;
}

第一种返回参数
int my_compare(const void *,const void *){
int a=1;
return a;
}
还是
第二种返回参数
int my_compare(const void *,const void *){
int compare_return(const void *,const void *);
return compare_return;
}
应该是哪一种返回参数???
...全文
112 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
pathuang68 2011-11-22
  • 打赏
  • 举报
回复
建议楼主看看这个:
函数指针的几种用法
character_w 2011-11-22
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 anyidan 的回复:]

int my_compare(const void *,const void *){
int compare_return(const void *,const void *); //函数声明
return compare_return; // 能编译通过?
}

int my_compare(const void *,const void *){
return(co……
[/Quote]
++
狂且 2011-11-22
  • 打赏
  • 举报
回复
学习了! 最近正在看函数指针!
AnYidan 2011-11-22
  • 打赏
  • 举报
回复
int my_compare(const void *,const void *){
int compare_return(const void *,const void *); //函数声明
return compare_return; // 能编译通过?
}

int my_compare(const void *,const void *){
return(compare_return(const void *,const void *)); //传入实参
}
vesapro 2011-11-22
  • 打赏
  • 举报
回复
你第二种也是返回的int型。
这么理解。 函数指针其实就是函数名 或者 (*函数名)
nanjingnew4 2011-11-22
  • 打赏
  • 举报
回复
求指导。。
nanjingnew4 2011-11-22
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 dizuo 的回复:]
第一种啊。。。
函数指针的类型由 函数的返回值,函数的形参 一起决定。
当然也可以进行类型转换。
[/Quote]
也就是这样写
compare my_compare(const void *,const void *){
int compare_return(const void *,const void *);
return compare_return;
nanjingnew4 2011-11-22
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 dizuo 的回复:]
第一种啊。。。
函数指针的类型由 函数的返回值,函数的形参 一起决定。
当然也可以进行类型转换。
[/Quote]
那如果
void my_sort(void *data, int length, int size, compare compareFunc)
在代码中提到的这个,compareFunc返回是不是第二种???
ryfdizuo 2011-11-22
  • 打赏
  • 举报
回复
第一种啊。。。
函数指针的类型由 函数的返回值,函数的形参 一起决定。
当然也可以进行类型转换。

69,371

社区成员

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

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