我正在尝试使用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 } };


这是结构

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 ++,而是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);

最佳答案

比较函数正在传递指向数组元素的指针。

man bsearch


  compar例程应该有两个指向密钥的参数
         对象和数组成员..


数组的元素类型为char *,因此compare函数应如下所示:

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

10-08 00:41