【发布时间】:2021-03-16 23:48:27
【问题描述】:
我想从文件中读取并基于它创建一个动态数组(用于使用 qsort())方法。我有以下代码来获取文件中的行数(满足特定条件,但不知道如何填充数组的各个元素)。
FILE* file = fopen("$filename", "r");
int count = 0; // Count num lines in the file
char buffer[50];
while(fgets(buffer, 50, file)) {
count++;
}
char** myArray;
myArray = malloc(count * sizeof(char*));
for (int i = 0; i < count; i++) {
myArray[i] = malloc(sizeof(char) * 51); // to include space for terminating character
}
// Re-open the file
fclose(file);
fopen("$filename", "r");
int ctr = 0; // Indexing for the array.
while(fgets(buffer, 50, file)) {
char* word = malloc(sizeof(char) * (strlen(buffer) + 1));
strcpy(myArray[ctr], word);
ctr++;
free(word);
}
for (int i = 0; i < count; i++) {
printf("%s\n", myArray[ctr]); // This just prints 7 new lines.
}
【问题讨论】:
-
附带说明:与关闭并重新打开文件相比,调用
fseek( file, 0, SEEK_SET );跳回文件开头会更简单。 -
在排序之前,您可能希望删除
fgets读入的换行符。有关执行此操作的最佳方法,请参阅以下问题:Removing trailing newline character from fgets() input -
你希望数组的每个条目是什么?文本文件的一个字符还是一行?
-
@AndreasWenzel 在我的实现中已经做到了这一点,但认为这与通常是这里的约定的“最小可重现示例”无关。感谢您提供有关 fseek 的提示
-
使用未初始化的
ctr,因此整个事物具有未定义的行为。word的内存泄漏。将未初始化的内存复制到myArray(strcpy is (dest, src))
标签: arrays c malloc dynamic-arrays