【发布时间】:2019-11-28 22:34:22
【问题描述】:
我正在编写一个简单的 c 程序,它将文本文件中的行读入 char **。在我的主函数中,我创建了 char * 数组,为其分配内存,并将指向该数组的指针传递给另一个函数,以使用 char * 填充数组中的每个索引,该 char * 表示文本文件中每一行的内容。
由于某种与我的内存管理相关的原因,我猜测,我在 while 循环的第三次迭代中收到分段错误,它将字符串复制到字符串数组中。这是为什么呢?
我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void getRestaurants(char ***restaurantsArray) {
FILE *restaurantsFile = fopen("./restaurants.txt", "r");
char *restaurant = (char *)malloc(50 * sizeof(char));
char *restaurantCopy = restaurant;
//fopen will return null if it is unable to read the file
if (restaurantsFile == NULL) {
free(restaurant);
return;
}
int index = 0;
while (fgets(restaurantCopy, 50, restaurantsFile)) {
// segfault occurs the third time the following line is executed
*restaurantsArray[index] = (char*)malloc(50 * sizeof(char));
strcpy(*restaurantsArray[index], restaurantCopy);
printf("%s", restaurantCopy);
printf("%s", *restaurantsArray[index]);
index++;
}
fclose(restaurantsFile);
free(restaurant);
}
void main() {
char **restaurantsArray = (char **)malloc(100 * sizeof(char *));
char **restaurantsArrayCopy = restaurantsArray;
getRestaurants(&restaurantsArrayCopy);
}
预期结果:
firstline
firstline
secondline
secondline
thirdline
thirdline
以此类推,如果提供的 restaurant.txt 文件包含:
firstline
secondline
thirdline
【问题讨论】:
-
为什么要使用三重指针?如果不修改值,为什么要通过引用传递参数?为什么要在函数外分配而在函数内释放?
标签: c arrays pointers segmentation-fault