【问题标题】:Allocating memory to a 3-dimensional char array causes segmentation fault将内存分配给 3 维 char 数组会导致分段错误
【发布时间】:2011-12-16 15:06:03
【问题描述】:

作为较早问题的一部分,我遇到了一些关于将内存分配给 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;
}

【问题讨论】:

  • 没有大括号,只有一个语句属于循环体。永远不要遗漏牙套! :-)

标签: c multidimensional-array char malloc


【解决方案1】:

你缺少一些大括号:

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

【讨论】:

  • 总是支撑结构的另一个原因,即使它们只有 1 行。
  • 嗯,非常感谢,懒惰确实是万恶之源;)
猜你喜欢
  • 2015-08-06
  • 2020-11-04
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多