【发布时间】:2021-08-23 23:18:45
【问题描述】:
我必须使用这两个函数动态分配内存,但我不断收到段错误。该代码从文件中获取字符串。我需要使用结构、指针和 malloc 为特定数量的怪物动态分配内存。
typedef struct monster {
char *name;
char *element;
int population;
} monster;
monster* createMonster(char *name, char *element, int population){
//Copying the data into the monster
monster *temp =(monster*) malloc(sizeof(monster));
strcpy(temp->name, name);
strcpy(temp->element, element);
strcpy(temp->population, population);
return temp;
free(temp);
}
monster** readMonsters(FILE* infile, int *monsterCount){
//getting monster count and creating temp pointers
monster **temp = NULL;
char m_word [8];
fscanf(infile, "%d", monsterCount);
fscanf(infile, "%s", m_word); //reading the word monster to skip it
char* temp_name;
char* temp_element;
int temp_pop;
//allocating memory and creating an array of monster pointers * mcount
temp = (monster**)malloc(*monsterCount * sizeof(monster*));
for(int i = 0; i < monsterCount; i++){
fscanf(infile, "%s",temp_name);
fscanf(infile, "%s",temp_element);
fscanf(infile, "%d",temp_pop);
monster *monster_temp = createMonster(temp_name, temp_element, temp_pop);
temp[i]->name = monster_temp->name;
temp[i]->element = monster_temp->element;
temp[i]->population = monster_temp->population;
}
return temp;
}
【问题讨论】:
-
请将
strcpy(temp->population, population);改为temp->population = population;,因为整数不是字符串。 -
scanf语句会出错,要么是因为没有为%s条目分配内存,要么是因为%d数据条目需要一个指针,例如fscanf(infile, "%d", &temp_pop);注意添加&请启用编译器警告。 -
编译器应该告诉你的错误更多,例如
i < monsterCount;应该是i < *monsterCount; -
除以上所有内容外,以
temp[i]->member = ....开头的三个赋值应替换为单个temp[i] = monster_temp;。仅供参考,createMonster中的free(temp);是无法访问的、不必要的,并且最终还是不正确的。它应该被删除。您从哪个参考指南学习 C,因为我可以建议您找到替代方法。 -
请发minimal reproducible example,以便我们重现问题并帮助您调试。
标签: c dynamic-memory-allocation