当我想跟踪内部结构中有多少项目时,我倾向于使用嵌套结构。所以我通常会做以下事情:
typedef struct Product {
char *name;
int qty;
} Prods;
typedef struct Category {
char *name;
int qty;
int prods_count;
Prods *prod;
} Cats;
然后我可以访问/释放数据:
Cats *cat = malloc(sizeof(Cats));
cat->prods_count = 10;
cat->prod = malloc(cat->prods_count, sizeof(Prods));
cat->prod[0].name = malloc(15);
strcpy(cat->prod[0].name, "Hello World!!!");
cat->prod[0].qty = 100;
for (i=0; i<cat->prods_count; i++)
free(cat->prod[i].name);
...
我想知道是否有办法只用一个来做到这一点struct
?