C-存储一系列字符串并循环直至文件结束



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

我的程序有两个问题。

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

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((,但这是毫无意义的,因为它只会在文件末尾返回,所以我将再次循环。

以下是代码: Note 它在您在最后一个do/wher wher wher wher wher wher wher wher wher wher the wher the wher the the the new the。

之前不会运行。
#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] = '';
        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

最新更新