C - 比较函数 - 需要解释

标签 c arrays string string-comparison

我正在阅读 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/

相关文章:

c - 为什么我的代码会出现无限循环?

c++ - 需要帮助理解遗留的 C 代码 _fmemcpy((LPSTR FAR *)Defdat,(LPSTR FAR *)&DLLdat,sizeof(DATSETTING));

c - 如何使用 MPI 中的标志打破所有进程中的循环?

jquery - 使用 jQuery,如何修改标签外的文本?

c++ - 字符串到 float 的转换?

Javascript For 不完成数组循环

arrays - 在 Swift 2 中从 segue 展开后 Tableview 不重新加载

php - MySQL left join,创建多维数组后

计算一个单词在文件中出现的次数

java - 在 java 中将字符串转换为日期时出现意外输出