我正在尝试编写一个函数来读取文本文件并将文本文件的每一行复制到传递给函数的数组的一行中。
void read_lines(FILE* fp, char*** lines, int* num_lines) {
int i = 0, line_count = 0;
char line[256], c;
fscanf(fp, "%c", &c);
while(!feof(fp)){
if(c == '\n') {
++line_count;
}
printf("%c", c);
fscanf(fp, "%c", &c);
}
rewind(fp);
*num_lines = line_count;
lines = (char***)malloc(line_count * sizeof(char**));
while (fgets(line, sizeof(line), fp) != NULL) {
lines[i] = (char**)malloc(strlen(line) * sizeof(char*));
strcpy(*lines[i], line);
}
++i;
}
}
初始部分扫描换行符,以便我知道最初分配给行的数量。我不确定哪里出错了。
此外,如果有人有任何资源可以帮助我更好地理解如何动态分配空间,我将不胜感激。
最佳答案
您应该了解指针的工作原理。在那之后,动态内存分配任务将变得非常微不足道。现在你的代码是完全错误的:
//here you assign to the argument. While this is technically allowed
//it is most certainly not what you have intended
lines = (char***)malloc(line_count * sizeof(char**));
while (fgets(line, sizeof(line), fp) != NULL) {
//sizeof(char*) <> sizeof(char). Also you need a space for the trailing \0
lines[i] = (char**)malloc(strlen(line) * sizeof(char*));
//[] precedes * so it is copying the string somewhere you not intend to
strcpy(*lines[i], line);
}
++i;
}
正确的版本应该是:
*lines = malloc(line_count * sizeof(char*));
while (fgets(line, sizeof(line), fp) != NULL) {
(*lines)[i] = malloc((strlen(line) + 1) * sizeof(char));
strcpy((*lines)[i], line);
}
++i;
}
请注意,您需要使用 (*lines)[i]
构造,因为 []
运算符在 *
(解引用)运算符之前.
关于c - 无法为字符串数组动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601475/