次の配列を作成しようとしています。
"Fruits", 25, {
{"Apple", 2},
{"Grapes", 13},
{"Melon", 10}
}
"Meats", 40, {
{"Beef", 9},
{"Chicken", 27},
{"Pork", 4}
}
...
私がこれまでに得たものを行うには、よりエレガントな方法があるように感じます。入力構造体を考慮して、この構造体をより効率的に作成する方法に関するフィードバック/サンプルをいただければ幸いです。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct Product {
char *name;
int qty;
} Prods;
typedef struct Category {
char *name;
int qty;
int prods_count;
Prods *prod;
} Cats;
typedef struct Inventory {
Cats *cat;
int cats_count;
} Inv;
struct tmp_input {
char name[12];
int qty;
char cat[12];
};
// return index if found
int in_array(Inv *inv, char *k) {
int i;
if (inv->cats_count == 0)
return -1;
for (i = 0; i < inv->cats_count; i++) {
if (strcmp (k, inv->cat[i].name) == 0) return i;
}
return -1;
}
int main () {
int i, j, exists = 0;
// temp struct.
struct tmp_input items[] = {
{"Apple", 2, "Fruit"}, {"Coke", 10, "Drink"}, {"Pork", 4, "Meat"},
{"Beef", 9, "Meat"}, {"Chicken", 27, "Meat"}, {"Melon", 10, "Fruit"},
{"Tea", 3, "Drink"}, {"Coffee", 20, "Drink"}, {"Grapes", 13, "Fruit"}
};
size_t len = sizeof (items) / sizeof (struct tmp_input);
Inv *inven = malloc(sizeof(Inv));
inven->cats_count = 0;
inven->cat = calloc(1, sizeof(Cats));
for (i = 0; i < len; i++) {
exists = in_array(inven, items[i].cat);
// category does not exist
if (exists == -1) {
inven->cat = realloc(inven->cat, sizeof(Cats) * (inven->cats_count + 1));
inven->cat[inven->cats_count].name = strdup(items[i].cat);
inven->cat[inven->cats_count].qty += items[i].qty;
inven->cat[inven->cats_count].prods_count = 1;
inven->cat[inven->cats_count].prod = calloc (1, sizeof (Prods));
inven->cat[inven->cats_count].prod->name = strdup (items[i].name);
inven->cat[inven->cats_count].prod->qty = items[i].qty;
inven->cats_count++;
}
// category found
else {
inven->cat[exists].qty += items[i].qty;
int size = inven->cat[exists].prods_count + 1;
inven->cat[exists].prod = realloc(inven->cat[exists].prod, sizeof(Prods) * (size));
inven->cat[exists].prod[size - 1].name = strdup (items[i].name);
inven->cat[exists].prod[size - 1].qty= items[i].qty;
inven->cat[exists].prods_count++;
}
}
for (i = 0; i < inven->cats_count; i++) {
printf("%3d %s\n", inven->cat[i].qty, inven->cat[i].name);
for (j = 0; j < inven->cat[i].prods_count; j++) {
printf("%3d %s\n", inven->cat[i].prod[j].qty, inven->cat[i].prod[j].name);
}
}
return 0;
}