c语言传递函数指针

来源:百度知道 编辑:UC知道 时间:2024/06/06 11:06:50
编写了一个比较两个数大小的函数~~
可是利用函数指针传递参数时出现错误~~

typedef int CmpFunc_t(const void *pKey1, const void *pKey2);

typedef struct {
struct Node *pRoot;
CmpFunc_t *cmp;
GetKeyFunc_t *getKey;
} BST_t;

BST_t *newBST(CmpFunc_t *cmp, GetKeyFunc_t *getKey);

const int intcmp(const void *var1, const void *var2) {
int var_1 = *(int*)var1;
int var_2 = *(int*)var2;

if(var_1 > var_2)
return 1;
else if(var_1 < var_2)
return -1;
else
return 0;
}

BST_t *pIntTree = newBST((GetKeyFunc_t*)intcmp, NULL);

在VC环境下编译时最后一行指针定义出现错误~~

错误如下~~

error C2664: 'newBST' : cannot convert parameter 1 from 'const void *(__cdecl *)(const void *)' to 'int (__cdecl *)(const void *,const void *)'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
BST_t *newBST(CmpFunc_t *cmp, GetKeyFunc_

intcmp是和GetKeyFunc_t对应起来的。
而你现在错在了CmpFunc_t这个函数参数上了。
你把怎样的函数参数指针传给了BST_t *newBST?
你没交代清楚啊,你把错误指针传给newBST函数的第一个参数,编译器肯定报错了。你给了那么多代码,关键你把什么传给了BST_t *newBST的第一个参数?给一下你调用这个newBST函数的代码,而且要你传给该函数第一个参数的参数定义。
另外给个建议:定义函数时,记得对传进来的参数进行合法性检验。多加几行代码是很有必要的,能增强函数的健壮性。(微软也好,ISO也好,都对大部分函数设计时要求做必要的合法检验)

#include <stdio.h>
char menu_select();

char main()
{
//菜单循环
while (1)
{
switch (menu_select())
{
case '1':
printf("Find\n"); break;
case '2':
printf("Graph\n"); break;
case '3':
printf("Goodbye!\n");
return '0';
default:
printf("Your input is illegal!\n");
}
}

//the end
return '0';
}

char menu_select()
{

char cn;
//输出菜单
printf("1.Find\n");
printf("2.Graph\n")