【发布时间】:2014-06-15 23:53:38
【问题描述】:
我不知道这里出了什么问题。尝试扫描名称列表: 鲍勃 蒂姆 托尼 艾莉森 吉姆
等等。进入双指针**字符串,但我不断收到段错误,看不到在哪里。
void insert_data(char **strings, const char *filename, int size)
{
int j = 0;
FILE* file = fopen(filename, "r");
if(file == NULL)
{
printf("File could not be opened");
return;
}
for(j=0; j<size; j++)
{
fscanf(file,"%s", strings[j]);
printf("%s\n", strings[j]);
}
fclose(file);
}
我有一个单独的函数来分配内存,但它仍然存在段错误
void allocate(char ***strings, int size)
{
strings = malloc(size * sizeof(char*));
if(strings == NULL)
{
printf("Could not allocate memory\n");
}
int i;
for(i=0;i<size;i++)
{
*(strings+i) = malloc(MAX_STRING_LEN * sizeof(char));
if(strings == NULL)
{
printf("Could not allocate memory\n");
}
}
}
【问题讨论】:
-
无法重现问题。
-
问题可能出在调用它的代码中。这里有一些小问题,例如没有测试
fscanf()的结果——你应该检查它是否返回 1,如果没有则退出循环——但总的来说它是合理的代码。请注意,您需要传递一个指针数组,而不是指向 2D 数组的指针,以使其工作。 -
你的
allocate函数错误。