我正在尝试使用bsearch,但搜索的结果一直保持NULL。我的名字数组按字母顺序排序。我是C的新手,需要你的帮助来了解我的错误。
这是一个数组
// arrays of children's names
char *chBamba[] = { "Bambale1", "Bamb2", "Bamb3", "Bambook4", "Bambookle5" };
char *chBisli[] = { "Bislile1", "Bischick2", "Bislile3", "Bis4" };
int nBamba = sizeof(chBamba) / sizeof(*chBamba);
int nBisli = sizeof(chBisli) / sizeof(*chBisli);
// array of workers
Worker a[] = { { "Printf", 10, NULL, 0 } ,{ "Bisli", 20, chBisli, nBisli },
{ "TapooChips", 3, chBamba, nBamba },{ "Bamba", 19, chBamba, nBamba } };
这是struct
typedef struct{
char name[LEN]; // worker's name
int salary; // worker's salary
char **childArr; // array of children names
int numChildren; // number of children}Worker;
比较功能
int compareNames(const void* child1, const void* child2){
char* ch1 = (char*)child1;
char* ch2 = (char*)child2;
return strcmp(ch1, ch2);
}
和bsearch
char childName[10];
char* nameFound;
printf("Please enter a child name to search for :");
scanf("%s",childName);
for (i = 0; i < 4; i++)
{
nameFound =(char*) bsearch(childName,a[i].childArr, a[i].numChildren, sizeof(a[i].childArr)/ sizeof(a[i].childArr[0]), compareNames);
}
它不是C ++。这就是我现在正在学习的东西。我正在使用VS 2015,它适用于C和C ++。我正在编辑一些更改以使其正常工作并进行编译。 所以比较是
int compareNames(const void * s1, const void * s2){
const char *key = (char*)s1;
const char * const *arg = (char**)s2;
return strcmp(key, *arg);
}
和bsearch是
nameFound = (char*)bsearch(childName,a[i].childArr, a[i].numChildren, sizeof(char*), compareNames);
答案 0 :(得分:1)
比较函数正在将指针传递给数组的元素。
来自man bsearch
:
compar
例程应该有两个指向键的参数 对象和数组成员....
数组元素的类型为char *
,因此比较函数应如下所示:
int compareNames(const void * pvchild1, const void * pvchild2)
{
const char ** ppc1 = (const char **) pvchild1; // casting necessary with C++
const char ** ppc2 = (const char **) pvchild2; // casting necessary with C++
return strcmp(*ppc1, *ppc2);
}
另外要涵盖数组包含空指针值的情况:
...
return strcmp(ppc1 ?*ppc1 :"", ppc2 ?*ppc2 :"");
}
像这样呼叫bsearch()
:
char * p = childName;
nameFound =(char*) bsearch( // casting necessary with C++
&p,
a[i].childArr,
a[i].numChildren,
sizeof *(a[i].childArr),
compareNames
);
另外作为旁注:您明确显示的代码不是 C而是C ++,因此
Worker a[] = {
{ "Printf", 10, NULL, 0 } ,{ "Bisli", 20, chBisli, nBisli },
{ "TapooChips", 3, chBamba, nBamba },{ "Bamba", 19, chBamba, nBamba }
};
不能在C中编译,但是给出错误:
error: initializer element is not constant