有必要按采集月份从小到大对所有记录进行分组。如果您决定不使用动态内存分配,那么它会按应有的方式从小到大排序,但是如果您更改代码,那么排序就不会那样工作。下面是按错误顺序排序的代码。
#include <stdio.h>
#include <stdlib.h>
#define COUNT_ITEMS 4
typedef struct Product {
char name[256];
int day;
int month;
int year;
int cost;
int count;
} Product;
void printinfo(const Product *prod)
{
printf("Product name: %s\n", prod->name);
printf("Date of purchase : %d.%d.%d\n", prod->day, prod->month, prod->year);
printf("Product price: %d\n", prod->cost);
printf("Number of products: %d\n", prod->count);
}
Product *prodRead() {
Product *prod;
prod = malloc(sizeof(Product));
printf("Enter name of a Product:\n");
scanf("%s", &prod->name);
printf("Enter day, month(number), year of purchase through a space:\n");
scanf("%d%d%d", &prod->day, &prod->month, &prod->year);
printf("Enter cost of product:\n");
scanf("%d", &prod->cost);
printf("Enter number of product:\n");
scanf("%d", &prod->count);
return prod;
}
int compMon(const void *a, const void *b) {
const Product *partOne = (Product *)a;
const Product *partTwo = (Product *)b;
return ((*partOne).month > (*partTwo).month) - ((*partOne).month < (*partTwo).month);
}
int main() {
Product *prod[COUNT_ITEMS];
for (int i = 0; i < COUNT_ITEMS; i++) {
prod[i]=prodRead();
printf("\n");
}
qsort(prod, COUNT_ITEMS, sizeof(Product*), compMon);
printf("Structura POSLE sortirovki \n");
for (int i = 0; i < COUNT_ITEMS; i++) {
printinfo(prod[i]);
printf("\n");
}
return 0;
}
输入数据(左)和输出数据(右):
A C
10 11 2020 6 6 2020
1000 600
2 1
B A
5 5 2019 10 11 2020
500 1000
3 2
C D
6 6 2020 3 3 2018
600 200
1 2
D B
3 3 2018 5 5 2019
200 500
2 3
指向数组元素的指针被传递给比较器,即
Product**,你认为有Product*。试试这样:
准备好代码:https ://ideone.com/f4ZgE7