我们目前正在进行一个项目,我们需要处理一些文本,为此我们需要将文本分成更小的部分。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct paragraph{
char **words;
}paragraph;
typedef struct text{
char name[100];
paragraph *list;
}text;
void readFileContent(FILE *file, paragraph *pa, int size){
char localString[100];
pa->words = (char **)malloc(size * sizeof(char *));
int i = 0, z;
while(fscanf(file, "%s", localString) == 1 && i < size){
z = strlen(localString);
pa->words[i] = (char *)malloc(z + 1);
strcpy(pa->words[i], localString);
i++;
}
}
void main(){
int i = 0, n, z;
FILE *file;
text *localText;
localText = (text *)malloc(sizeof(text));
openFile(&file, "test.txt");
i = countWords(file);
i = i / 50 + 1; // calculate the number of section need for the text
localText->list = calloc(sizeof(paragraph *), i);
for(n = 0; n < i ; n++){
printf("Paragraph - %d\n", n);
readFileContent(file, &localText->list[i], 50);
}
for(n = 0; n < i ; n++){
printf("Paragraph - %d", n);
for(z = 0; z < 50; z++){
printf("no. %d\n", z);
printf("%s\n", localText->list[n].words[z]);
}
}
}
当我尝试运行该程序时,我在底部的打印循环中遇到了段错误。我认为这是由内存分配问题引起的,但我不明白为什么。
更新 1 我已将代码更改为使用 3 维数组来存储文本段,但是当我尝试使用 malloc 分配内存时,我仍然遇到段错误。
localText->list[i][n] = malloc(100 * sizeof(char));
她是修改后的代码。
typedef struct {
char name[100];
char ***list;
}text;
int main(){
int i = 0, n, z,wordCount, sections;
FILE *file;
text *localText;
openFile(&file, "test.txt");
wordCount = countWords(file);
sections = (wordCount / 50) + 1;
localText = malloc(sizeof(text));
localText->list = malloc(sections * sizeof(char **));
for(i = 0; i < sections; i++)
localText->list[i] = malloc(50 * sizeof(char *));
for(n = 0; n < 50; n++)
localText->list[i][n] = malloc(100 * sizeof(char));
readFileContent(file, localText->list, 50);
freeText(localText);
return 1;
}
最佳答案
您的代码中有很多错误。以下是最严重的:
1) 指针到指针不是多维数组。如果您使用指向指针的指针访问多维、动态分配的数组,则该数组需要以对指向指针的指针有意义的方式进行分配。
看起来您正在尝试动态分配一个指针数组,然后为该数组中的每个指针分配一个数据数组。但是,您的代码不会这样做,您的代码有太多的间接级别,没有任何意义。例如paragraph *list;
,为什么需要指向包含指向指针的指针的结构的指针?
您需要简化数据结构。我建议改为这样做:
typedef struct {
char name[100];
char** list;
} text;
2) 不要将 typedef 命名为与 struct 标记相同的东西,这迟早会让您陷入 namespace 冲突的麻烦。在 typedef:ing 结构时,您甚至不需要结构标记,而是按照我上面的示例进行操作。
3) 切勿强制转换 C 语言中 malloc/calloc 的结果。这隐藏了编译器警告和错误。关于原因的无数详细帖子可以在这里找到,在SO .
4) 因为这是一个在操作系统上运行的托管程序(我可以通过使用文件处理来判断),main 只能返回 int。将 main 的定义更改为 int main()
或者它不会在标准 C 编译器上编译。
5) for(n = 0; n < i ; n++) ... list[i]
.正如您通过自己的代码可以看出的那样,使用变量名 i
并不是一个好主意。除了循环迭代器之外的任何东西。 ( i
实际上代表迭代器)。这就是为什么你在那里遇到错误。
6) 您必须在完成后关闭打开的文件,通过 fclose()
.
7) 当你用完动态分配的内存时,你必须通过free()
释放它。 .
关于c - malloc 问题导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8519027/