提问人:Azizbek Sattorov 提问时间:10/27/2023 最后编辑:GerhardhAzizbek Sattorov 更新时间:10/27/2023 访问量:85
C 上的 struct 任务中的 struct
struct in struct task on C
问:
我正在开发获取信息表单文件“stockroom.txt”和从“产品.txt”获取的程序,然后它将数据存储在以下类型的结构中的文件中:
// data from "stockroom.txt"
struct ingredient {
char* name;
int number;
};
struct dose {
int index;
int amount;
};
// here data from products.txt
struct recipe {
char* name;
int price;
int number_ing;
int current_price;
int best_price;
struct dose* ingredients;
};
因此,当我想读取文件“products.txt”并将其数据存储到结构中时,会出现问题。具体而言,我有以下功能:
void read_recipes(int nr, int ni, struct recipe* recipes[], struct ingredient* ingredients[], FILE* products){
int i, j, k;
for (i = 0; i < nr; i++){
char tmp_s[31];
int tmp_n, n;
fscanf(products, "%s %d %d", tmp_s, &tmp_n, &n);
recipes[i] = (struct recipe *)malloc(sizeof(struct recipe));
recipes[i] -> name = strdup(tmp_s);
recipes[i] -> price = tmp_n;
recipes[i] -> number_ing = n;
recipes[i] -> current_price = 0;
recipes[i] -> best_price = 0;
recipes[i] -> ingredients = NULL;
for(j = 0; j < n; j ++){
char tmp_name[21];
int tmp_amount;
struct dose* doses[n];
doses[j] = (struct dose*)malloc(sizeof(struct dose));
fscanf(products, "%s %d", tmp_name, &tmp_amount);
for(k = 0; k < ni; k++){
if(strcmp(ingredients[k] -> name, tmp_name) == 0){
doses[j] -> index = k;
doses[j] -> amount = tmp_amount;
}
}
recipes[i] -> ingredients = doses; // error here?
}
}
}
可能错误在最后一行,但我不确定。让我澄清一下我想要什么。
文件“stockroom.txt”包含以下内容:
6
flour 35
sugar 40
eggs 20
milk 25
cocoa 48
jam 10
第二个文件:
3
Easter_eggs 6 2
cocoa 8
milk 3
Sacher_cake 22 3
flour 4
cocoa 14
jam 2
Mimosa_cake 13 5
eggs 3
flour 4
sugar 6
milk 4
jam 2
结构剂量*成分包含来自储藏室的产品指数和产品数量。但是,通过调试,我了解到它不会保存所有信息,而只会保存最后一行。请帮帮我。
代码的最后一行,我期待错误,gcc 写这个
从类型“struct dose **”分配到类型“struct dose”时类型不兼容
如何解决,我不知道。
答:
1赞
Azizbek Sattorov
10/27/2023
#1
这些更改解决了以下问题:
// ...
recipes[i] -> ingredients = (struct dose*)malloc(sizeof(struct dose) * n);
for(j = 0; j < n; j ++){
char tmp_name[21];
int tmp_amount;
struct dose* ingredient = (struct dose*)malloc(sizeof(struct dose));
fscanf(products, "%s %d", tmp_name, &tmp_amount);
for(k = 0; k < ni; k++){
if(strcmp(ingredients[k] -> name, tmp_name) == 0){
ingredient -> index = k;
ingredient -> amount = tmp_amount;
}
}
recipes[i] -> ingredients[j] = *ingredient;
}
评论
1赞
Lundin
10/27/2023
请注意,您还需要局部变量,否则您将创建内存泄漏。 创建结构内容的硬拷贝,但循环完成后,指针仍指向分配的副本。在这种情况下,您可能只是将其分配为局部变量并跳过 malloc。free()
ingredient
recipes[i] -> ingredients[j] = *ingredient;
ingredient
评论
doses[j]
doses
doses
malloc
doses
struct ingredient
ingredients
struct recipe
ingredients
struct dose