【发布时间】:2016-07-18 07:24:46
【问题描述】:
我正在使用 C 做一个包含数组的学校项目。目前我正在尝试按字母顺序对字符串数组进行排序。我似乎无法成功地做到这一点。这是我到目前为止所做的简化代码:
void sort_string_array(char **table)
{
int i = 0;
while (table[i++] != NULL); // to get the length
qsort(table, i, sizeof(char *), strcmp); // sorting
}
这是一个完全错误的解决方案风格,我关闭了吗,有什么问题:P?任何帮助都会很棒!
编辑:
void sort_string_array(char **table)
{
int i = 0;
while (table[i] != NULL) i++; // to get the length
qsort(table, i, sizeof(char *), strcmp); // sorting
}
更正该错误后,它仍然无法正常运行。使用字符串 {'one','two','three','four'} 这种排序的第一个值应该是 'four' 但它是 'two'}
【问题讨论】:
-
这段代码不起作用吗?
-
@2501,比较函数是
strcmp:) -
你不能直接使用
strcmp作为比较函数:它有错误的参数类型。你需要为它做一个包装函数。 -
单步调试代码并在调试器中观察
i的值。不到 5 分钟就能找到错误。