【发布时间】:2018-10-15 21:19:20
【问题描述】:
我有一个 malloc 的字符数组列表,如下所示。
list= (char**)malloc(LIST_SIZE* sizeof(*list));
for (int i = 0; i < LIST_SIZE; i++)
list[i] = (char*)malloc(sizeof(char) * 33);//33 is the size of each element in the list
列表的大小可以增加到 25,000(LIST_SIZE) 或者有时可能只有 10 个元素或更少。
我的 compare() 函数会出错。
int compare(const void * a, const void * b)
{
const char **fpa = (const char**)a;
const char **fpb = (const char**)b;
return strcmp(*fpa, *fpb);
//return *(char *)a - *(char*)b;//This one also does not work
}
qsort() 是这样调用的。我怀疑它失败是因为它被调用的方式,但我不明白为什么。
qsort(list, current_list_element_count, 33, compare);
【问题讨论】:
-
qsort(list, current_list_element_count, sizeof *list, &compare); -
@Stargateur 你的意思是我为什么要使用幻数?或者为什么是 33 号?
-
没关系,我没有看到
list[i] = (char*)malloc(sizeof(char) * 33);,但正如 dbush 所说,这不是预期的大小qsort() -
OT:这个
const char **fpa = (const char**)a;应该是char * const *fpa = a;。 -
OT^2:无需投射
malloc()。至少如果你真的会使用 C 而不是 C++。