gpt4 book ai didi

C qsort 嵌套结构数组

转载 作者:行者123 更新时间:2023-11-30 19:39:41 26 4
gpt4 key购买 nike

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

当我尝试对整数或结构数组执行相同的操作时,它工作得非常好。然而,当我开始使用嵌套结构时,它开始核心转储。

当前输出是:

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;
}

最佳答案

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

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

因此您需要将相同的大小传递给qsort

qsort(列表, 6, sizeof(记录), 比较);

应该是

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

或者更好

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

关于C qsort 嵌套结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36235718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com