2011-12-16 95 views
1

作为较早问题的一个自旋,我遇到了一些关于将内存分配给三维数组的问题。将内存分配给三维字符数组会导致分段错误

我正在研究一个项目,我们需要在文本上做一些工作。为此,我们需要将文本分成更小的部分,并逐字处理文本。为了保存这些较小的文本片段,我们有一个3D数组,每个片段列表包含该部分中的单词列表。

但是当我尝试使用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; 
} 
+3

W/O支架只有一条语句属于循环体。永远不要留下大括号! :-) – ckruse 2011-12-16 15:16:11

回答

6

你缺少一些括号:

for(i = 0; i < sections; i++) { 
// ... 
} 
+2

(+1)斑点! – NPE 2011-12-16 15:12:16