from input file to array using malloc and realloc

后端 未结 2 469
渐次进展
渐次进展 2021-01-24 07:56

I am trying to read input from a file and put each string in an array using malloc and realloc. So if the input file is :

alex
john
jane
smith

2条回答
  •  走了就别回头了
    2021-01-24 08:35

    you would want to allocate an array of pointers first with an initial size say 10:

    int size = 10;
    char **inputFile= malloc(sizeof*inputFile*size);
    

    Then for each word you read you allocate more memory for it and insert it into the array:

    char line[100];
    fscanf(file, "%s", line);
    inputFile[index++] = strdup(line);
    

    Now check if you need more words then you realloc the array:

    if (index==size) {
       size += 10;
       inputFile = realloc(inputFile, sizeof*inputFile*size);
    }
    

    So you end up with something like this:

    [0]->"alex"
    [1]->"john"
    [2]->"jane"
    [3]->"smith"
    

    When you're done you need to loop over the array and free each string and then free the array, this part is left as an exercise :)

提交回复
热议问题