C - 比较功能 - 需要解释
C - Comparison function - Need explanation
我目前正在阅读 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)
只会比较两个数组中的第一个字符串,但如果这些字符串匹配,则会 return 0 (= equality)。该代码甚至不会查看第二个、第三个等索引处的字符串。
此方法真的只比较两个数组中的第一个字符串还是我遗漏了什么?
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.
你误会了这是干什么用的。 "To sort an array of pointers to strings ..."。这是关于对单个数组进行排序,不超过一个数组。
int cmp(const void* a, const void* b)
{
const char* s1 = (const char*)*a;
const char* s2 = (const char*)*b;
return strcmp(s1, s2);
}
cmp
函数获取指向两个字符串 (char*) 的指针,qsort
希望比较的不是整个字符串数组
我目前正在阅读 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)
只会比较两个数组中的第一个字符串,但如果这些字符串匹配,则会 return 0 (= equality)。该代码甚至不会查看第二个、第三个等索引处的字符串。
此方法真的只比较两个数组中的第一个字符串还是我遗漏了什么?
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.
你误会了这是干什么用的。 "To sort an array of pointers to strings ..."。这是关于对单个数组进行排序,不超过一个数组。
int cmp(const void* a, const void* b)
{
const char* s1 = (const char*)*a;
const char* s2 = (const char*)*b;
return strcmp(s1, s2);
}
cmp
函数获取指向两个字符串 (char*) 的指针,qsort
希望比较的不是整个字符串数组