作为先前问题的衍生,我遇到了一些有关将内存分配给 3 维数组的问题。
我正在做一个项目,我们需要在文本上做一些工作。为此,我们需要将文本分成更小的部分,并逐字处理文本。为了保存这些较小的文本片段,我们有一个 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;
}
最佳答案
你缺少一些牙套:
for(i = 0; i < sections; i++) {
// ...
}
关于c - 将内存分配给 3 维字符数组会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8536014/