且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将bsearch与字符串数组一起使用时出现问题

更新时间:2023-02-06 11:00:48

由于您使用的是const char *数组,因此bsearch()会将指向这些元素的指针传递给比较函数.换句话说,它将在第二个参数中接收const char * const *.

Since you are using an array of const char *, bsearch() will pass to the comparison function a pointer to those elements. In other words, it will receive const char * const * in its second argument.

int myStrCmp(const void *s1, const void *s2) {
  const char *key = s1;
  const char * const *arg = s2;
  printf("myStrCmp: s1(%p): %s, s2(%p): %s\n", s1, key, s2, *arg);
  return strcmp(key, *arg);
}