【问题标题】:Sorting array of structs对结构数组进行排序
【发布时间】:2015-12-09 14:00:00
【问题描述】:

我已经定义了一个结构数组

typedef struct sorting {
    int number
} SRT;

SRT *mystr = NULL;

我后来动态分配的。 我想按number int 对其进行排序;

我必须编写什么样的函数才能让 qsort 执行它?我写过:

qsort(mystr,array_index,sizeof(mystr),magic);

int magic(const void *a, const void *b) {
    int one=((const struct mystr*)a)->number;
    int two(( const struct myst*)b)->number;

    return ( one-two);
}

但它没有工作。我该怎么做? 它抛出了关于不命名类型的错误。

【问题讨论】:

  • 如果出现“不起作用”,请准确发布 what 不起作用。在这种情况下,发布编译器错误会更容易回答问题。
  • 还有,应该是one - two
  • @Lundin:这种草率的比较在微妙的方面存在缺陷。看我的回答。

标签: c sorting qsort


【解决方案1】:

您无法使用编写的函数可靠地对数组进行排序:

  • 它有语法错误,其中一些是拼写错误,另一些则表明类型、结构标记和变量名之间存在混淆。

  • return (one - two); 仅适用于相当小的 onetwo 值。如果存在整数算术溢出,它将调用未定义的行为。比如one == INT_MAXtwo == -1,C语言没有指定one - two的值,在普通平台上很可能返回负值INT_MIN,导致排序不正确。

一个简单的解决方案是这样的:

int sort_function(const void *a, const void *b) {
    int one = ((const SRT*)a)->number;
    int two = ((const SRT*)b)->number;

    return (one > two) - (one < two);
}

如果one 小于two,则表达式(one &gt; two) - (one &lt; two) 的计算结果为-1,如果它们相等则为0,否则为1。在 C 中,如果为假,则比较结果为 0,如果为真,则为 1

排序功能应该这样使用:

qsort(mystr, array_count, sizeof(*mystr), sort_function);
  • 第二个参数是mystr指向的数组中结构的数量。
  • 第三个参数是单个结构的大小:sizeof(mystr) 是指针的大小,而不是指向的大小。
  • 避免使用像 magic 这样的神秘名称...对类型、函数和变量使用描述性名称。

【讨论】:

    【解决方案2】:

    两个问题:

    qsort(mystr,array_index,sizeof(mystr),magic);
    

    mystr 是指向SRT 的指针,因此您传递的是指向结构的指针的大小,而不是结构的大小:

    qsort(mystr,array_index,sizeof(STR),magic);
    

    然后是这个:

    int one=((const struct mystr*)a)->number;
    int two(( const struct myst*)b)->number;
    

    mystr 是变量名,而不是类型,myst 没有在任何地方定义。您需要这里的类型名称:

    int one=((const SRT *)a)->number;
    int two=((const SRT *)b)->number;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多