将文本从txt文件解析为C中的多维数组

Parsing senteces from a txt file to a multidimensional array in C

这让我发疯。我试图从 txt 文件中解析每个句子(即点之间的所有字符)并将每个句子插入一个数组。最终目标是拥有一个多维数组,每个句子作为单个数组。 我设法达到了我认为它应该工作的地步,但我从 numOfRow++

行收到分段错误(核心转储)错误
void parseRows(FILE* file){
    int c;
    int numOfRow = 0;
    int numOfChar = 0;
    int numOfRows = countNumOfRows(file);
    fseek(file, 0, SEEK_SET); // Reset file pointer position to the beginning
    char **rows = malloc(numOfRows*sizeof(char*));
    for (int i=0; i < numOfRows; i++) rows[i] = malloc(1000*sizeof(char));

    while ((c=fgetc(file))!= EOF) {   
        if (c != '.') {
            rows[numOfRow][numOfChar] = c;
            numOfChar++;
        } else {
            rows[numOfRow][numOfChar] = '[=10=]';
            numOfRow++;       // This is throwing the error              
            numOfChar = 0;            
        }
    }
    printOutput(rows, numOfRows);
}

如果我注释掉该行,程序将覆盖第一个数组中的每一行,结果我只得到最后一句话,所以我知道它正在运行。 我错过了什么?

完整代码在这里:

#include <stdio.h>
#include <stdlib.h>
#define USAGE "USAGE: ./huffman <textFile.txt>\n"

FILE* openFile(char[]);
void parseRows(FILE*);
int countNumOfRows(FILE*);
void printOutput(char**, int);

int main(int argc, char** argv){
    FILE* fd;
    if (argc != 2) printf("%s", USAGE);

    fd = openFile(argv[1]);
    parseRows(fd);
}

FILE* openFile(char* file){
    FILE* stream;
    stream = fopen(file, "r");
    return stream;
}

int countNumOfRows(FILE* file){
    int i = 0;
    char c;
    while ((c=fgetc(file))!= EOF) {   
        if (c == '.') i++;
    }
    printf("numero di righe %d\n", i);
    return i;
}

void parseRows(FILE* file){
    int c;
    int numOfRow = 0;
    int numOfChar = 0;
    int numOfRows = countNumOfRows(file);
    fseek(file, 0, SEEK_SET); // Reset file pointer position to the beginning
    char **rows = malloc(numOfRows*sizeof(char*));
    for (int i=0; i < numOfRows; i++) rows[i] = malloc(1000*sizeof(char));

    while ((c=fgetc(file))!= EOF) {   
        if (c != '.') {
            rows[numOfRow][numOfChar] = (char)c;
            numOfChar++;
        } else {
            rows[numOfRow][numOfChar] = '[=11=]';    
            numOfRow += 1;               
            numOfChar = 0;            
        }
    }
    printOutput(rows, numOfRows);
}

void printOutput(char** matrix, int rows){
    for (int i=0; i<rows; i++){
        printf("%s", matrix[i]);
    }
}

输入文件示例 textFile.txt:

Any text that contains more than one sentence.
This Should get parsed and return a 2 dimension array with every sentence as single array.

您的 countNumOfRows() 函数计算文件中的点数,然后使用该数字为数组分配 space。但是,在最后一个点之后和 EOF 之前可能有更多字符(例如 CR 或 LF 或 CRLF),因此您可以轻松地写入 malloc 内存的末尾。

尝试:

return (i + 1)

在 countNumOfRows() 的末尾,看看是否消除了段错误。