【问题标题】:Can't access a 3d array in a struct defined in my .h file无法访问我的 .h 文件中定义的结构中的 3d 数组
【发布时间】:2011-12-17 14:16:42
【问题描述】:

我的 main.h 中有一个结构,但是当我尝试为结构中的 3D 数组分配内存时,出现以下编译器错误。

    'text' has no member named 'list'

现在,我只为 3D 数组获取结构中的其他变量。

main.h

#define MAX_WORD 100

typedef struct textTag {
   char name[100];
   char  ***list;
   int words;
}text;

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"

void createArray(FILE *file, text *checkTexts, int fileCount,  int size){
   int i, n, wordCount, sections, rest;
   FILE *textFile;
   text localText;
   char fileName[MAX_WORD + 30];

   readFileNames(file, checkTexts);

   for(i = 0; i < fileCount; i++){
      localText = checkTexts[i];

      strcpy(fileName, "./testFolder/");
      strcat(fileName, checkTexts[i].name);
      openFile(&textFile, fileName);

      checkTexts[i].words = countWords(textFile);

      sections = (wordCount / size);
      rest = wordCount % size;
      checkTexts[i].list = malloc(sections * sizeof(char **)); //Compile error here

      for(n = 0; n < sections; n++){
         checkTexts[i].list[n] = malloc(size * sizeof(char *)); //Compile error here
      }

      checkTexts[i].list[sections] = malloc(rest * sizeof(char*)); //Compile error here

      readFileContent(textFile,checkTexts[i].list, size); //Compile error here

   }

}

【问题讨论】:

  • 请包含编译错误
  • 您只提到了编译器错误,但没有提到您收到的确切错误。你需要提到它。
  • 编译器说 main.c:170:20: error: 'text' has no member named 'list'
  • 用于定义结构的 sn-p 是否都在 main.h 文件中?如果没有,你能显示整个文件吗?您的代码在 gcc 4.5 下编译得很好,但我在源文件中定义了内联文本。
  • 无法复制。注释掉带有未定义函数的行并定义 MAX_WORD,gcc -W -c main.c 仅警告可能未初始化使用 wordCount

标签: c multidimensional-array struct


【解决方案1】:
  1. checkTexts 可能未初始化 - 您可以使用来自 assert.hassert() 处理此问题
  2. 尝试ddd 在执行期间查看您的指针。这是查看问题所在的最佳方法之一。

也许这也有帮助: http://c-faq.com/aryptr/ 尤其是 6.2、6.3、6.8。

【讨论】:

  • 等等,你从哪里得到你的信息。我一直在试图追查 malloc 返回值过度转换的来源,它在这个网站上的家庭作业问题中很猖獗,通常是问题的原因。
  • 类型转换会导致哪些问题?通过强制转换,您有时可以更轻松地跟踪错误,因为报告了类型不匹配,如果您遇到问题,您应该仔细检查您的分配。
  • 如果您忘记包含 stdlib.h,这意味着 malloc 将返回 int 而不是 void*,这会导致 sizeof(int) != sizeof(void*) 出现问题。强制转换将阻止编译器警告您。
  • 在我看来,不包括 stdlib 更糟糕。如果您使用函数,则应确保使用正确的声明。这只是一个关心的问题。这两种方式都可能导致问题,所以我编辑了我的帖子;)。
  • 我同意不包括 stdlib 会更糟。但我最近看到很多问题,人们不必要地将 malloc 返回值转换为错误的东西。
【解决方案2】:

就像我在评论中所说的那样。

解决了问题

这是我自己犯的一个愚蠢的错误,我不小心打开了错误的 main.h 文件,所以我正在为另一个项目编辑一个文件,所以我使用的结构确实没有 en 成员列表。

但感谢您尝试帮助我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2018-12-17
    • 2017-01-15
    相关资源
    最近更新 更多