作为早期问题的一个重点,我遇到了一些关于将内存分配给三维数组的问题.
我正在开发一个项目,我们需要在文本上做一些工作.为此,我们需要将文本拆分为较小的部分,并逐字处理文本.为了保存这些较小的文本,我们有一个3D数组,一个部分列表,每个部分包含该部分中单词的列表.
但是当我尝试使用单个单词分配内存时,我遇到了分段错误malloc().
localText->list[i][n] = malloc(100 * sizeof(char));
Run Code Online (Sandbox Code Playgroud)
这是整个代码.
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, …Run Code Online (Sandbox Code Playgroud) 我们目前正在开发一个需要处理某些文本的项目,为此,我们需要将文本分成较小的部分.
#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 …Run Code Online (Sandbox Code Playgroud)