【问题标题】:qsort structure array deletes everythingqsort 结构数组删除所有内容
【发布时间】:2013-04-20 06:57:09
【问题描述】:

所以我在使用 qsort 对结构数组进行排序时遇到了麻烦。

我以这个链接为例:http://support.microsoft.com/kb/73853

当我运行程序时,它会为结构中的原始名称提供空白,并为 gp 的所有值提供零。

typedef int (*compfn)(const void*, const void*);

struct record
{
    char player[20];
    int gp;
};
struct record entries[15];

int compare(struct record *, struct record *);


void show ()           
{
    int v;
    qsort((void *)entries, 10, sizeof(struct record), (compfunc)compare);
    struct record *p = entries;
    for(v=0;v<counter;v++, p++)
    {
         printf("%s ..... %d \n", p->player , p->gp);
    }
}

int compare(struct record * p1, struct record * p2)
{
     if( p1->gp < p2->gp)
         return -1;
     else if (p1->gp > p2->gp)
         return 1;
     else
         return 0;
}

编辑:大家好,非常感谢你们的帮助,但是,我已经尝试了你们所说的一切,它仍然只是将所有值都归零

【问题讨论】:

  • 这不应该编译。
  • 除了 (compfunc) 到 (compfn) 它对我有用

标签: c arrays struct qsort


【解决方案1】:

您的通话可以简化,无需转换为void *

qsort(entries, 10, sizeof entries[0], compare);

注意使用sizeof entries[0] 以避免数组类型的无意义重复。

比较函数也不应该强制转换,因为它应该被简单地定义为匹配原型:

static int compare(const void *a, const void *b)
{
  const struct record *ra = a, *rb = b;

  if( ra->gp < rb->gp)
     return -1;
  if (ra->gp > rb->gp)
     return 1;
  return 0;
}

顺便说一下,为了提供信息,这里有一个经典的 (?) 方法来简化您有时会在这些地方看到的 3 路测试:

return (ra->gp < rb->gp) ? -1 : (ra->gp > rb->gp);

我不反对支持这种表达方式,尤其是如果你是初学者,但我认为我会包括它,因为它是相关的,并且可能具有指导意义。 p>

【讨论】:

  • 我见过的“经典”方式是return (ra-&gt;gp &gt; rb-&gt;gp) - (ra-&gt;gp &lt; rb-&gt;gp);
  • 我见过的“经典”方式是return (ra-&gt;gp - rb-&gt;gp),但我不知道windows的qsort是否要求比较函数的结果在{-1,0,1}中, linux qsort 没有。
【解决方案2】:

除了 microsoft 支持页面一团糟而且不是学习 C 的好来源之外,您的代码在此处缺少&amp;

...
qsort((void *)entries, 10, sizeof(struct record), (compfunc)compare);
... 

应该是

...
qsort((void *)&entries, 10, sizeof(struct record), (compfunc)compare);
... 

还有,我想你是想写

...
qsort((void *)&entries, 15, sizeof(struct record), (compfn)compare);
... 

【讨论】:

  • 在表达式中使用时,数组名称会隐式转换为指针。
  • @luserdroog 我知道。我只是想尽可能贴近 microsoft 支持页面和 OP 提供的代码。
  • 哦,我明白了。我没有费心去看那个页面。我想知道他们为什么不写(void *)(struct record *)&amp;entries[0]:更清楚。 :)
  • 是的,我什至使用微软页面的唯一原因是因为在 stackoverflow 上的一个 smilar 问题上,有人发布了该链接并说这是一个很好的例子哈哈
  • @user2322610 哦,在这种情况下,请查看 unwind 的答案或 qsort (linux.die.net/man/3/qsort) 的联机帮助页
猜你喜欢
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
相关资源
最近更新 更多