【发布时间】:2012-01-21 02:04:06
【问题描述】:
我们目前正在进行一个项目,我们需要处理一些文本,为此我们需要将文本分成更小的部分。
#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;
}
【问题讨论】:
-
你应该在调试器中运行你的程序。当它崩溃时,您将能够检查变量的值。
-
这是我第一次看到
for (n = 0; n < i; n++)而不是for (i = 0; i < n; i++)... -
@BlagovestBuyukliev:这可能是这里错误的根本原因。使用
i绑定数组是个坏主意。