我是 C 新手,目前正在学习如何动态分配内存。目前,我正在尝试创建一个动态分配的字符数组,其中每个字符串的内存也是动态分配的。每个字符串都是从 txt 文件中的一行中检索的(numIngredients = 行数 | MAX_ING = 每行/成分的最大字符数)。
char** readIngredients(int numIngredients){
FILE *in;
in = fopen("input.txt", "r");
char** ingredients;
ingredients = (char**)malloc(numIngredients*sizeof(char));
for(int i=0; i<numIngredients; i++){
ingredients[i] = (char*)malloc(MAX_ING*sizeof(char));
}
for(int i=0; i<numIngredients; i++){
fscanf(in, "%s", ingredients[i]);
}
fclose(in);
return ingredients;
}
当我声明成分时,分割错误似乎发生了......我做错了什么
您没有为指针数组分配足够的内存:
ingredients = (char**)malloc(numIngredients*sizeof(char));
相反,您numIngredients
为 size 的元素分配空间sizeof(char)
。这会导致您超出分配的内存触发未定义的行为。
乘以 a 的大小char *
,所以:
ingredients = malloc(numIngredients*sizeof(char *));
或者甚至更好:
ingredients = malloc(numIngredients*sizeof(*ingredients));
因为它不依赖于ingredients
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句