1

排序部分:

      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函数之后,结构数组没有正确排序,稍后会引发段错误。

4

1 回答 1

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 指向的比较函数按升序排序,该函数使用两个指向被比较对象的参数调用。如果认为第一个参数分别小于、等于或大于第二个参数,则该函数应返回一个小于、等于或大于零的整数。

于 2012-08-30T15:45:24.663 回答