【问题标题】:Reading and populating a dynamic array in C在 C 中读取和填充动态数组
【发布时间】: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


【解决方案1】:

您可以简化代码:

  • 无需分配指针数组中的所有行,只需在读取文件时分配行。
  • 无需关闭并重新打开文件,只需rewind() 流。

这是修改后的版本:

char **read_file(const char *filename, int *countp) {
    FILE *file = fopen(filename, "r");
    int count = 0; // Count num lines in the file
    char buffer[200];

    while (fgets(buffer, sizeof buffer, file)) {
        count++;
    }
    
    char **myArray = malloc(count * sizeof(char *));
    if (myArray == NULL) {
        fclose(file);
        return NULL;
    }
    
    rewind(file);
    
    int ctr = 0; // Indexing for the array.
    
    while (ctr < count && fgets(buffer, sizeof, file)) {
        // you might want to strip the trailing newline
        //buffer[strcspn(buffer, "\n")] = '\0';
        myArray[ctr++] = strdup(buffer);
    }
    fclose(file);
    
    for (int i = 0; i < ctr; i++) {
        printf("%s", myArray[i]);
    }
    *countp = count;
    return myArray;
}

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2011-12-18
    • 1970-01-01
    相关资源
    最近更新 更多