在 C 中读取和填充动态数组

问题描述

我想从文件中读取并基于它创建一个动态数组(用于使用 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,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.
}

解决方法

您可以简化代码:

  • 无需分配指针数组中的所有行,只需在读取文件时分配行即可。
  • 无需关闭并重新打开文件,只需 glmnet_cv1_nosuperdoc = po("learner_cv",glmnet_lrn,id = "glmnet",affect_columns = selector_invert(selector_name("superdoc"))) ensemble2 = glmnet_cv1_nosuperdoc %>>% log_reg_lrn e2learner = as_learner(ensemble2) # etc. 流。

这是修改后的版本:

rewind()