【问题标题】:C qsort array of nested structsC qsort 嵌套结构数组
【发布时间】:2016-03-26 13:13:29
【问题描述】:

我正在尝试对结构记录数组进行排序。由于某种原因,核心转储不断发生。

当我尝试对一个整数或结构数组做同样的事情时,它工作得非常好。但是,当我开始使用嵌套结构时,它开始转储核心。

当前输出为:

Before sorting
first last 0  
first last 1  
first last 2  
first last 3  
first last 4  
first last 5  

AFTER sorting  
Segmentation fault (core dumped)

编译器:Cygwin

typedef struct {
    char last[NAMESIZE]; /* last name (1 word) */
    char first[NAMESIZE]; /* first name (1 word) */
} name;

typedef struct {
    name name;
    int score; /* score (between 0 & 100 inclusive) */
} record;

int compare (const void * a, const void * b){
    const record *recordA = (record *)a;
    const record *recordB = (record *)b;
    printf("%d: %d", recordA->score, recordB->score);
    return ( recordB->score - recordA->score );
}

int main (){
    record ** list;
    int i;
    list=malloc(6*sizeof(record*));
    printf("Before sorting\n");
    for(i=0; i<6; i++){ 
        list[i]=malloc(sizeof(record));
        strcpy(list[i]->name.first,"first");
        strcpy(list[i]->name.last,"last");
        list[i]->score=i;   
    }
    for (i=0; i<6; i++){
        printf ("%s %s %d\n",list[i]->name.first, list[i]-    >name.last,list[i]->score);         
    }

    printf("AFTER sorting\n");
    qsort (list, 6, sizeof(record), compare);
    for (i=0; i<6; i++){
        printf ("%s %s %d\n",list[i]->name.first, list[i]- >name.last,list[i]->score);         
    }    
  return 0;
}

【问题讨论】:

  • 您的代码中没有struct record 数组。您有一组指向struct record指针。这就是您要尝试的qsort。因此,您的代码中的所有其他内容都应该相应地重写。你打电话给qsort 不正确。您的比较函数不正确。

标签: c arrays struct coredump qsort


【解决方案1】:

list 是一个由 6 个指向 record 的指针组成的数组:

list=malloc(6*sizeof(record*));

所以你需要将相同的大小传递给qsort

qsort (list, 6, sizeof(record), compare);

应该是

qsort (list, 6, sizeof(record*), compare);

或者更好

qsort (list, 6, sizeof(*list), compare);

【讨论】:

    【解决方案2】:

    我同意第一个答案。但有一点很清楚,你不应该使用 qsort (list, 6, sizeof(record), compare) ,其中 sizeof(record) 将返回记录的总字节数,但不会自动计算名称使用的字节数。 也不 qsort (list, 6, sizeof(record), compare) ,其中 sizeof(record) 将返回 record* 的 4 个字节,因为它是一个指针。 相反,我认为也许您只需要自己计算字节数并在数据结构记录中添加另一个数据,例如名称大小

    【讨论】:

      【解决方案3】:

      如果您有两个记录的比较函数,您希望将它们分配给指向指向记录的常量的指针。

      在你的 qsort 中,我猜你已经传入了你的记录列表数据结构,所以元素的数量将是你所使用的。

      /*Comparison function: Score ascending only.*/
      int cmp_sasc(const void *p, const void *q){
          record * const *pp = p;
          record * const *qq = q;
          return (*pp)->score - (*qq)->score;
      }
      

      【讨论】:

      • 为什么我需要将它们分配给指向一个记录的常量的指针?将它们分配给比较函数中的指针以将 void * 转换为适当的指针不是重点吗?
      猜你喜欢
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多