C - 此 COD 接收包含日期的文件并打印它们。然后订购它们,但我收到一个奇怪的输出,我无法为 qsort 制作正确的函数



这是代码读取的文件类型

1998年10月20日

2029年12月1日

2002年1月22日

1997年1月5日

1998年10月19日

只是一系列的约会。read_file函数应该将这些日期存储到日期结构指针列表中,但一旦我尝试将月份转换为数字(使排序更容易(,我就会收到这种奇怪的输出

1924802780

十月

1924802780

12月

1924802780

一月

0

一月

0

十月

在这里,我首先打印转换后的月份,然后打印文件中读取的月份。当然,10月份应该是的第9名

另外,第二个问题是,datecmp函数工作得很好,但如果我从库中调用qsort函数,我会收到这个警告

prova.c:127:33:警告:传递'int(struct-date*,struct date(转换为类型为int(_Nonnull(的参数(const void*,constvoid*('[-Wincompatible指针类型]qsort(list,n,sizeof(list(,datecmp(;^~~~~~~/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/stdlib.h:161:22:注意:将参数传递到此处的参数'__compar'int(_Nonnull__compar((常量void*,常量void*((;

我应该如何修改datecmp函数来解决这个问题?

感谢的帮助

这是代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct date {
int day;
int month;
int year;
};
struct date *Read_File(FILE *f, int *n)
{
int i;
int dim = 4;
char month[20];
char buf[250];
struct date *list;
list = malloc(dim * sizeof(*list));
if (list == NULL) {
(*n) = 0;
free(list);
return NULL;
}
while (fgets(buf, sizeof(buf), f) != NULL) {
i = sscanf(buf, "%d %s %d", 
&list[*n].day,  month, &list[*n].year);
if (i < 3) {
puts("wrong number of elements");
return NULL;
}
if (!(strcmp(month, "January")))
list[*n].month = 0;
else if (!(strcmp(month, "febrary")))
list[*n].month = 1;
else if (!(strcmp(month, "march")))
list[*n].month = 2;
else if (!(strcmp(month, "april")))
list[*n].month = 3;
else if (!(strcmp(month, "may")))
list[*n].month = 4;
else if (!(strcmp(month, "june")))
list[*n].month = 5;
else if (!(strcmp(month, "july")))
list[*n].month = 6;
else if (!(strcmp(month, "august")))
list[*n].month = 7;
else if (!(strcmp(month, "september")))
list[*n].month = 8;
else if (!(strcmp(month, "October")))
list[*n].month = 9;
else if (!(strcmp(month, "november")))
list[*n].month = 10;
else if (!(strcmp(month, "December")))
list[*n].month = 11;
(*n) = (*n) + 1;
printf("n %d n", list[i].month);
printf("n %s n", month);
if ((dim) == (*n)) {
dim *= 2;
list = realloc(list, dim * sizeof(*list));
}
if (list == NULL) {
(*n) = 0;
free(list);
return NULL;
}
}
return list;
}
//int datecmp(struct data *data1, struct data *data2)
int datecmp(struct date *date1, struct date *date2)
{
if (date1->year == date2->year) {
if (date1->month == date2->month) {
if (date1->day == date2->day)
return 0;
else if (date1->day > date2 -> day)
return 1;
else
return -1;
} else if (date1->month > date2-> month) {
return 1;
} else {
return -1;
}
} else if (date1->year > date2->year) {
return 1;
} else {
return -1;
}
}
int main(int argc, char *argv[])
{
FILE *f;
struct date *list;
int n = 0;
int i;
if (!(f = fopen(argv[1], "r")))
return 0;
if (!(list = Read_File(f, &n)))
return 0;
fclose(f);
qsort(list , n, sizeof(*list), datecmp);
free(list);
fclose(f);
return 0;
}

qsort()需要(对的引用(一个比较例程,该例程用两个参数定义为const void *,并返回一个int;例如:

int datecmp(const void *a, const void *b)
{
struct date *date1 = (struct date *) a, *date2 = (struct date *) b;
...
return (...);
}

最新更新