我正在阅读 Engineering a Sort Function 并尝试理解以下有关比较函数的内容:
To sort an array of len-byte strings with terminal null characters, use the standard string- comparison routine, strcmp: qsort(a, n, len, strcmp);
To sort an array of pointers to strings, use strcmp with another level of indirection. int pstrcmp(char **i, char **j) { return strcmp(*i, *j); }
字符串比较很清楚,但对于字符串指针数组的比较则不然。我认为 strcmp(*i, *j) 只会比较两个数组中的第一个字符串,但如果这些字符串匹配,将返回 0 (= 相等)。该代码甚至不会查看第二个、第三个等索引处的字符串。
这个方法真的只是比较两个数组中的第一个字符串还是我遗漏了一些东西?
最佳答案
I think strcmp(*i, *j) will just compare the first strings in both arrays but will return 0 (= equality) if these strings match. The code won't even look at the strings at the 2nd, 3rd, etc. index.
您误解了它的用途。 “对指向字符串的指针数组进行排序...”。这是关于对单个数组进行排序,而不是多个数组。
关于C - 比较函数 - 需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252443/