2011-12-16 44 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