【发布时间】:2021-08-02 02:34:15
【问题描述】:
这是我的Book 结构,这是我的代码:
typedef struct book {
char title[100];
char author[20];
int price;
} BOOK;
#define MAX_SIZE 10
int comparePrice(const void *bookA, const void *bookB);
int count = 0;
int main() {
BOOK *books[MAX_SIZE]; // here is array of struct pointers
while (1) {
char title[100] = "";
char author[20] = "";
int price = -1;
//////////// printf select menu ////////////
int selector = -1;
scanf("%d", &selector);
switch (selector) {
case 1:
while (getchar() != '\n');
printf("--------input book data--------\n");
printf("title :");
gets(title);
printf("author :");
gets(author);
printf("price :");
scanf("%d", &price);
books[count] = (BOOK *) malloc(sizeof(BOOK));
memset(books[count], 0, sizeof(BOOK));
strcpy(books[count]->title, title);
strcpy(books[count]->author, author);
books[count]->price = price;
count++;
break;
case 4:
printf("--------sorting price--------\n");
qsort(books, count, sizeof(BOOK), comparePrice);
for (int i = 0; i < count; ++i) {
printf("%d. title: %s author: %s price: %d\n", i + 1, books[i]->title, books[i]->author, books[i]->price);
}
break;
default:
for (int i = 0; i < MAX_SIZE; ++i) {
free(books[i]);
books[i] = NULL;
}
return 0;
}
}
}
int comparePrice(const void *bookA, const void *bookB) {
const BOOK *a = (const BOOK *)bookA;
const BOOK *b = (const BOOK *)bookB;
return b->price - a->price;
}
但qsort 不工作
选择 4 号菜单,该程序停止。
我尝试调试,发现 a 和 b 有未知值。
而在打印排序结果的printf语句中出现EXC_BAD_ACCESS错误。
我需要做些什么来进行排序。
【问题讨论】:
-
pssst,如果你使用
calloc,你不需要自己把memset的一切都设为0。任何你忘记free,所以你有内存泄漏。和getsis evil。strcpy也很危险。 -
不错的编辑,但不能保证
books数组有MAX_SIZE元素。因此,您可能正在尝试释放未初始化的指针。使用count。 -
@YIGeon 你想按降序排序吗?
-
@VladfromMoscow 是的!
标签: arrays c pointers struct qsort