示例代码:
- #include
- #include
- #include
-
- static Comp(const void *a, const void *b)
- {
- char *pa = (char *)a;
- char *pb = (char *)b;
-
- return strcmp(a, b);
- }
-
- int main(void)
- {
- char strs[3][10] = { "bd", "am", "kn" };
- qsort(strs, 3, sizeof(strs[0]), Comp);
- for (int i = 0; i < 3; ++i) {
- printf("%s ", strs[i]);
- }
-
-
- return 0;
- }
运行结果:
说明:传参时不可使用 qsort(strs【0】, 3, sizeof(strs[0]), Comp),原因:strs 被解释为一个数组类型,被认定为 strs[0] 具有 3 * 10 = 30 字节,而实际仅仅具有 10 字节,会发生内存写越界,后果不可预料。
示例代码:
- #include
- #include
- #include
-
- static Comp(const void *a, const void *b)
- {
- char *pa = (char *)a;
- char *pb = (char *)b;
-
- return strcmp(a, b);
- }
-
- int main(void)
- {
- char strs[3][10] = { "bd", "am", "kn" };
- qsort(strs[0], 3, sizeof(strs[0]), Comp);
- for (int i = 0; i < 3; ++i) {
- printf("%s ", strs[i]);
- }
-
-
- return 0;
- }
编译结果: