为什么使用qsort函数的代码在C中不起作用?

时间:2012-08-30 15:38:55

标签: c pointers struct qsort

排序部分:

      order = (struct order_s **) calloc(pm->len - q, sizeof(struct order_s*));

      for (i = 0; i < window_pos; ++i) {
              order[i] = (struct order_s *) malloc(sizeof(struct order_s));
              order[i]->pos = i;
              order[i]->good = good[i];
      }
      for (i = window_pos + q; i < pm->len; ++i)
      {
              order[i-q] = (struct order_s *) malloc(sizeof(struct order_s));
              order[i-q]->pos = i;
              order[i-q]->good = good[i];
      }
     qsort(order, pm->len - q, sizeof(struct order_s *), compare);

比较功能:

int compare (const void * a, const void * b)
{
        if ((((const struct order_s *)a)->good - ((const struct order_s *)b)->good) > 0)
                return 1;
        else
                return -1;
}

结构:

struct order_s {
  int pos;
  double good;
};

值:

(gdb) p pm->len
$35 = 20
(gdb) p window_pos 
$36 = 1
(gdb) p q
$37 = 5

在qsort()之前:

(gdb) p *order[0]
$2 = {pos = 0, good = 1.3238653863672125}
(gdb) p *order[1]
$3 = {pos = 6, good = 0.96180564211148134}
(gdb) p *order[2]
$4 = {pos = 7, good = 1.0684181637005736}
(gdb) p *order[3]
$5 = {pos = 8, good = 0.92113662370476379}

在qsort()之后:

(gdb) n
(gdb) p *order[0]
$6 = {pos = 0, good = 1.3238653863672125}
(gdb) p *order[1]
$7 = {pos = 6, good = 0.96180564211148134}
(gdb) p *order[2]
$8 = {pos = 7, good = 1.0684181637005736}
(gdb) p *order[3]
$9 = {pos = 8, good = 0.92113662370476379}

qsort函数之后,结构数组没有正确排序,稍后会抛出段错误。

1 个答案:

答案 0 :(得分:2)

compare()函数参数是指针到数组的元素。在这种情况下,数组的元素是struct order*,这意味着compare()的参数是struct order**,而不是struct order*

更改为:

int compare (const void * a, const void * b)
{
    const struct order_s** aa = a;
    const struct order_s** bb = b;

    /* Can two 'order_s' instances never be equal ? */
    if ( (*aa)->good - (*bb)->good) > 0) return 1;
    else  return -1;
}

来自C99标准部分 7.20.5.2 qsort功能

  

根据比较,数组的内容按升序排序   compar指向的函数,,用两个指向的参数调用   被比较的对象。该函数应返回小于,等于或的整数   如果第一个参数被认为分别小于,等于或大于第二个参数,则大于零。