存储字符串数组并循环直到文件末尾

Storing an array of strings and looping until end of file

我正在编写一个程序,其中我需要完成的任务之一是将文本文件(其名称通过命令行提供)的每一行存储为单独的字符串以供将来操作。

我的程序有两个问题。

首先是将字符串存储在数组中的问题。当我用字符串分配数组索引时,一切正常。但是一旦我 free() 用于分配另一个字符串的字符串,两个字符串都会被删除。

userText[numStrings - 1] = currentString; 
/* Both userText at index and currentString hold the same value at this point */
free(currentString);
/* Both userText at index and currentString are free'd */

这可能是一件我不理解的简单事情,我对 C 还是很陌生。

我遇到的第二个问题是,我不知道如何循环到文件末尾。我知道 feof() 存在,但这有点毫无意义,因为它只会 return true 直到文件结束后,所以我将再次循环。

这是代码:注意它不会运行直到你在最后一个do/while循环中设置一些条件。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(int argc, char** argv){

    char** userText = NULL;
    char* currentString = NULL;
    int currentStringSize = 0;
    int numStrings = 0;


    FILE* fp = fopen(argv[1],"r");


    do{

        numStrings++;
        currentStringSize = 0;
        do{
            currentStringSize++;
            currentString = (char*)realloc(currentString, currentStringSize * sizeof(char));
            fscanf(fp, "%c", &currentString[currentStringSize - 1]);

        }while(!(currentString[currentStringSize - 1] == '\n'));
        currentString[currentStringSize - 1] = '[=11=]';

        userText = (char**) realloc(userText, numStrings * sizeof(char*));

        for (int i = 0; i < numStrings; i++){
            userText[i] = (char*) realloc(userText[i], currentStringSize * sizeof(char));
        }

        userText[numStrings - 1] = currentString;
        free(currentString);
        currentString = NULL;
        } while (//the end of the file *insert code here*);


    for (int i = 0; i < numStrings; i++){
        free(userText[i]);
    }
    free(userText);
    fclose(fp);

    return 0;
}

谢谢你的帮助。

这些行很有问题:

for (int i = 0; i < numStrings; i++){
    userText[i] = (char*) realloc(userText[i], currentStringSize * sizeof(char));
}

userText[numStrings - 1] = currentString;
free(currentString);

首先你为userText[i]分配内存,覆盖userText中已经存在的指针。

然后你简单地覆盖你分配的最后一个指针,使你失去你刚刚分配的。

最后释放 userText[numStrings - 1] 指向的内存(该指针和 currentString 都指向同一内存)。

所有这些问题的解决方案很简单:只要做

userText[numStrings - 1] = currentString;

就是这样!这就是您所需要的。


并且如评论中所述,您 do 需要使 currentString 成为空指针,然后返回到循环顶部并调用 realloc.