C qsort结构数组删除所有内容

C qsort结构数组删除所有内容,c,arrays,struct,qsort,C,Arrays,Struct,Qsort,因此,我在使用qsort对结构数组进行排序时遇到困难 我以这个链接为例: 当我运行该程序时,它会为最初在结构中的名称提供空格,并为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 *)

因此,我在使用qsort对结构数组进行排序时遇到困难

我以这个链接为例:

当我运行该程序时,它会为最初在结构中的名称提供空格,并为
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;
}
typedef int(*compfn)(常量无效*,常量无效*);
结构记录
{
字符播放器[20];
int-gp;
};
结构记录条目[15];
int比较(结构记录*,结构记录*);
无效显示()
{
INTV;
qsort((void*)条目,10,sizeof(struct record),(compfunc)compare;
结构记录*p=条目;
对于(v=0;vplayer,p->gp);
}
}
int比较(结构记录*p1,结构记录*p2)
{
如果(p1->gpgp)
返回-1;
否则如果(p1->gp>p2->gp)
返回1;
其他的
返回0;
}

编辑:大家好,非常感谢你们的帮助,但是,我已经尝试了你们说的每一句话,它仍然将所有内容的值都变成零。除了microsoft支持页面非常混乱而且不是学习C的好来源之外,您的代码缺少一个
&
,这里:

...
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);
... 

您的通话可以简化,无需强制转换到
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;
}
静态整数比较(常量无效*a,常量无效*b)
{
常量结构记录*ra=a,*rb=b;
如果(ra->gpgp)
返回-1;
如果(ra->gp>rb->gp)
返回1;
返回0;
}
顺便说一句,仅供参考,这里有一个经典的(?)方法来简化三向测试,你有时会在这样的地方看到:

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

我不赞成这种表达方式,尤其是如果你是初学者的话,但我认为我应该把它包括在内,因为它是相关的,而且可能对你有指导意义。

这不应该编译。除了(compfunc)到(compfn),它对米雷名称的作用在表达式中使用时会隐式转换为指针。@luserdroog我知道。我只是想尽可能地遵守microsoft支持页面和OP提供的代码。哦,我明白了。我懒得看那一页。我想知道他们为什么不写
(void*)(struct record*)和条目[0]
:更清楚。:)是的,我使用微软网页的唯一原因是因为有人在stackoverflow上的一个微笑问题上发布了这个链接,并说这是一个很好的例子haha@user2322610哦,在这种情况下,看看unwind的答案或qsort()的主页,我看到的“经典”方式是
return(ra->gp>rb->gp)-(ra->gpgp)
我看到的“经典”方法是
return(ra->gp-rb->gp)
,但我不知道windows的qsort是否要求比较函数的结果在{-1,0,1}中,linux qsort不需要。