c - 如何通过 qsort 对 C 中的 3D 字符数组进行排序

标签 c arrays sorting qsort multidimensional-array

我在使用 C 语言中的 qsort() 对 3D 字符数组进行排序时遇到问题。 我想按字符串的长度对数组进行排序。

我找到了用于对二维数组进行排序的代码:

int compare(const void *name1, const void *name2)
{
    const char *name1_ = *(const char **)name1;
    const char *name2_ = *(const char **)name2;

    return strcmp(name1_, name2_);
}

我将代码修改为:

int compare(const void *name1, const void *name2)
{    

    const char *name1_ = *(const char ***)name1;
    const char *name2_ = *(const char ***)name2;

    if(strlen(name1_)>strlen(name2_))
    {
      return 1;
    }

    if(strlen(name1_)<strlen(name2_))
    {
      return -1;
    }
    else
    {
      return 0;
    }
}

但这不起作用,我不知道该怎么做。

例如。我想像这样对数组进行排序:

char * array1 [][2] = {
     { "murderer", "termination specialist" },
     { "failure", "non-traditional success" },
     { "specialist", "person with certified level of knowledge" },
     { "incorrect answer", "alternative answer" }
    };

此格式:

char * array1 [][2] = {
         { "incorrect answer", "alternative answer" }, 
         { "specialist", "person with certified level of knowledge" },
         { "murderer", "termination specialist" },
         { "failure", "non-traditional success" }
        };

最佳答案

在不知道您想要引入的排序规则的情况下,我可以在您的实现中看到 C 指针问题。如果代码成功用于 2D 案例:

const char name1_ = *(const char **)name1;

我的猜测是 3D 案例的类型转换不正确:

const char name1_ = *(const char ***)name1;

因为这应该是

const char name1_ = **(const char ***)name1;

因为在 3D 情况下,您需要取消引用指针两次。

关于c - 如何通过 qsort 对 C 中的 3D 字符数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20275227/

相关文章:

python - 在不重复上一项的情况下在 Python 中对列表进行排序

c - 如何管理硬件缓存使用

java - HashMap 有支持数组,那为什么它是无序的

spring - REST 排序以负 ('-' ) 符号降序,而不是 <propertyName>.dir=desc

C:固定长度数组,转储最旧的、移动并添加最新的

javascript - jQuery/javascript 在列表中查找值

arrays - 对长度为 n 的未排序数组的 t 个最小整数进行排序

c - 指示 GDB 6.5 使用目标文件中嵌入的源代码

c++ - C 和 C++ 中使用的不同版本的 exec 是什么?

C 操作位串中的位