C语言结构体指针嵌套item数组声明与数据扫描异常问题求助
问题修正方案
你的代码存在4处核心错误,对应修改方法如下:
错误列表
- 你标注的malloc行多余添加了
**前缀:itemList本身就是item*类型的指针,直接接收malloc返回值即可,多余的双星会触发非法内存访问。 fscanf读取整数参数错误:需要传入变量的地址,你当前直接传递结构体成员的值,会触发内存访问异常。- 数组遍历没有使用下标:循环中始终访问
itemList的第一个元素,无法正确写入后续item的数据。 totalParts未初始化就累加:字段初始值为随机垃圾值,最终计算结果必然不符合预期。
修正后代码
#include <stdlib.h> #include <stdio.h> // 假设infile为已正确打开的全局文件指针 FILE* infile; typedef struct item { int itemID; int numParts; } item; typedef struct recipe { int numItems; item* itemList; int totalParts; } recipe; recipe* readRecipe() { int i; recipe *smoothieList; smoothieList = (recipe*)malloc(sizeof(recipe)); // 初始化总份数为0 smoothieList->totalParts = 0; fscanf(infile, "%d", &smoothieList->numItems); printf("%d", smoothieList->numItems); // 移除多余的**,正确为itemList分配内存 smoothieList->itemList = (item*)malloc(sizeof(item)* smoothieList->numItems); for(i=0; i<smoothieList->numItems; i++) { // 用下标访问第i个item,传入变量地址给fscanf fscanf(infile, "%d", &smoothieList->itemList[i].itemID); fscanf(infile, "%d", &smoothieList->itemList[i].numParts); smoothieList->totalParts += smoothieList->itemList[i].numParts; } return smoothieList; } recipe** readAllRecipes(int *numRecipes) { recipe** smoothieList; int i; smoothieList = (recipe**)malloc(sizeof(recipe*) * (*numRecipes)); for(i=0; i<*numRecipes; i++) { smoothieList[i] = readRecipe(); printf("%d", smoothieList[i]->numItems); } return smoothieList; }
额外注意事项
使用完申请的内存后需要按顺序释放,避免内存泄漏:先释放每个recipe的itemList,再释放每个recipe实例,最后释放存储recipe指针的数组。
内容的提问来源于stack exchange,提问作者DreaperA
相关产品推荐
相关产品推荐

