因此,我试图在名为conj_str的字符串数组中进行二进制搜索,我必须对它进行排序,而我试图使用qsort的问题是比较功能无法正常工作,并且不对任何内容进行排序。
程序:
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
#define MAX_CHARS 1024
#define MAX_SIZE 10000
int compare (const void *a, const void *b)
{
const char *key = a;
const char * const *arg = b;
return strcmp(key, *arg);
}
int main()
{
int i;
char conj_str[MAX_SIZE][MAX_CHARS];
size_t len = sizeof(conj_str)/sizeof(const char *);
strcpy(conj_str[0],"fcb");
strcpy(conj_str[1],"bvb");
strcpy(conj_str[2],"slb");
strcpy(conj_str[3],"fcp");
strcpy(conj_str[4],"rma");
qsort (conj_str, len, sizeof (const char *), compare);
for (i = 0; i < 5; i++) {
printf ("%d: %s\n", i, conj_str[i]);
}
int j = (int*) bsearch("fcb",conj_str,len,sizeof(const char *),compare);
puts("found") ? j > 0 : puts("not found");
}
正在通话中
qsort (conj_str, len, sizeof (const char *), compare);
错误指定了数组元素的大小。必须有
qsort (conj_str, len, sizeof ( char[MAX_CHARS]), compare);
也有此声明
int j = (int*) bsearch("fcb",conj_str,len,sizeof(const char *),compare);
没有意义。
并且在比较函数中此声明
const char * const *arg = b;
也没有道理。