如何从stdlib为qsort编写比较函数?

dim*_*ish 4 c sorting compare qsort

我有一个结构:

struct pkt_
{
  double x;
  double y;
  double alfa;
  double r_kw;
};

typedef struct pkt_ pkt;
Run Code Online (Sandbox Code Playgroud)

这些结构的表格:

pkt *tab_pkt;

tab_pkt = malloc(ilosc_pkt * sizeof(pkt));
Run Code Online (Sandbox Code Playgroud)

我想要做的是排序tab_pkttab_pkt.alfatab_pkt.r:

qsort(tab_pkt, ilosc_pkt, sizeof(pkt), porownaj);
Run Code Online (Sandbox Code Playgroud)

porownaj是比较函数,但如何写呢?这是我的"草图":

int porownaj(const void *pkt_a, const void *pkt_b)
{
  if (pkt_a.alfa > pkt_b.alfa && pkt_a.r_kw > pkt_b.r_kw) return 1;
  if (pkt_a.alfa == pkt_b.alfa && pkt_a.r_kw == pkt_b.r_kw) return 0;
  if (pkt_a.alfa < pkt_b.alfa && pkt_a.r_kw < pkt_b.r_kw) return -1;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ble 12

这样的事情应该有效:

int porownaj(const void *p_a, const void *p_b)
{
  /* Need to store arguments in appropriate type before using */
  const pkt *pkt_a = p_a;
  const pkt *pkt_b = p_b;

  /* Return 1 or -1 if alfa members are not equal */
  if (pkt_a->alfa > pkt_b->alfa) return 1;
  if (pkt_a->alfa < pkt_b->alfa) return -1;

  /* If alfa members are equal return 1 or -1 if r_kw members not equal */
  if (pkt_a->r_kw > pkt_b->r_kw) return 1;
  if (pkt_a->r_kw < pkt_b->r_kw) return -1;

  /* Return 0 if both members are equal in both structures */
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

远离愚蠢的技巧,如:

return pkt_a->r_kw - pkt_b->r_kw;
Run Code Online (Sandbox Code Playgroud)

返回非标准化值,令人困惑的读取,对浮点数不能正常工作,有时甚至对于整数值也不能正常工作的棘手角落情况.