如何访问结构中不是第一个-Qsort的元素



我正在尝试对以下结构进行排序。我正在使用qsort根据出版日期按最新的第一本的顺序订购书籍。我完全不明白为什么指针不能访问date published元素。

#include <string.h>
#include <stdlib.h>
#include "problem5.h"
int int_cmp(const void *a, const void *b)
{
//const int *ia = (const int *)a;
//const int *ib = (const int *)b;
//return *ia - *ib;
return (*(int*)a - *(int*)b);
}

int main()
{
struct book* books = NULL;     // no books at all initially so we initialize to NULL
// so we can simply use realloc
int numberofbooks = 0;
int programend = 0;
while (programend == 0)
{
printf("1. Add Bookn");
printf("2. View Booksn");
printf("3. Quitn");
int command;
int i, j;
scanf("%d", &command);
if (command == 1)
{
getchar();   // consume Enter key (due su scanf)
// allocate memory for one more book
books = realloc(books, sizeof(struct book) * (numberofbooks + 1));
printf("Enter Namen");
gets(books[numberofbooks].name);
printf("Enter Authorn");
gets(books[numberofbooks].author);
printf("Enter Year Publishedn");
scanf("%d", &books[numberofbooks].year_published);
numberofbooks++;   // increment number of books
printf(books.year_published);
}
else if (command == 2)
{
qsort(books->year_published, numberofbooks, sizeof(int), int_cmp);
for (i = 0; i < numberofbooks; i++)
{
printf("%d - %s by %sn", books[i].year_published, books[i].name, books[i].author);
}
}
else if (command == 3)
{
programend = 1;
}
//else if and the else will prevent infinite loop when the user enters invalid choice in the beginning.
else if (command != 1 || command != 2 || command != 3)
{
printf("Invalid choice!n");
}
else {return 0;}
}
free(books);
return 0;
}

我认为问题出在qsort((中的指针上,但我不知道如何纠正。我尝试使用qsort(图书,图书数量,sizeof(int(,int_cmp(;但这些书并没有按预期订购。

下面是一个多关键字排序的例子:

int
cmp_multikey(const void *a,const void *b)
{
const struct book *booka = a;
const struct book *bookb = b;
int cmp;
do {
// sort by year published
cmp = booka->year_published - bookb->year_published;
if (cmp)
break;
// sort by author
cmp = strcmp(booka->author,bookb->author);
if (cmp)
break;
// sort by title
cmp = strcmp(booka->name,bookb->name);
if (cmp)
break;
} while (0);
return cmp;
}

使用调用

qsort(books,numberofbooks,sizeof(struct book),cmp_multikey);

其他一些提示。。。

[正如其他人所提到的]永远不要使用gets。使用switch/case而不是if/else梯形图。

尽量避免scanffgets混用。

就我个人而言,我更喜欢[总是]使用fgets。以下是gets的[安全]替代品和scanf("%d",&num);的替代品:

int
getstr(const char *prompt,char *buf,int buflen)
{
char *cp;
printf("%s",prompt);
fflush(stdout);
cp = fgets(buf,buflen,stdin);
if (cp == NULL) {
fprintf(stderr,"unexpected EOFn");
exit(1);
}
// find newline
cp = strchr(buf,'n');
// ensure we had enough space
if (cp == NULL) {
fprintf(stderr,"response too large for buffern");
exit(1);
}
// strip newline
*cp = 0;
}
int
getnum(const char *prompt)
{
char buf[1000];
int num;
getstr(prompt,buf,sizeof(buf));
num = atoi(buf);
return num;
}

相关内容

最新更新