具有彼此类型的变量的结构

时间:2014-01-08 16:17:00

标签: c

我有两个结构DirFileArraydirFile,其中包含其他类型的变量。我的Eclipse IDE对此很生气,因为第一个结构看不到第二个类型('dirFile'无法解析)。如何使两个结构相互看见?

struct dirFile;

我在顶部添加了一行,但这没有帮助。

struct DirFileArray {
  dirFile *array;
  size_t used;
  size_t size;
}

struct dirFile
{
    int  contentType ;
    char name [STR_SHORT];
    struct DirFileArray * content;
};

4 个答案:

答案 0 :(得分:0)

使用前瞻声明:

struct dirFile;

struct {
  dirFile *array;
  size_t used;
  size_t size;
} DirFileArray;

struct dirFile
{
    int  contentType ;
    char name [STR_SHORT];
    struct DirFileArray * dirFile;
};

答案 1 :(得分:0)

一个简单的前向声明就可以了。

您可以查看typedef更复杂的包含问题

struct dirFile;

struct {
  dirFile *array;
  size_t used;
  size_t size;
} DirFileArray;

struct dirFile
{
    int  contentType ;
    char name [STR_SHORT];
    struct DirFileArray * dirFile;
};

答案 2 :(得分:0)

如果你真的想这样做,请使用前向声明。

typedef struct DirFileArray_s DirFileArray;
typedef struct dirFile_s dir_File;

struct DirFileArray_s {
    ...
}

struct DirFileArray_s {
    ...
}

我建议双重思考,因为这样的嵌套很讨厌。

答案 3 :(得分:0)

您需要“转发声明这些数组”。还记得当你学会使用稍后定义的函数时,你做了什么?你会写:

int func_to_be_defined_later(int param); /* for example */

int main(void)
{
    return func_to_be_defined_later(10);
}

int func_to_be_defined_later(int param)
{
    return param + 1;
}

它与结构类似:

/* forward declaration */
struct DirFileArray;
struct dirFile;

struct DirFileArray {       /* note: you had misplaced the struct name */
    struct dirFile *array;  /* note: you forgot struct */
    size_t used;
    size_t size;
};

struct dirFile
{
    int  contentType ;
    char name [STR_SHORT];
    struct DirFileArray *dirFile;
};

值得注意的是,您只能指向来转发声明的结构(包括声明的结构),而不是它们的变量。原因是编译器知道如何分配指针以及给它多少空间,但它不知道如何分配结构以及它是什么sizeof

实际上,有两个结构包含另一个类型的变量,或者包含其自身类型的变量(不是指针)的结构,这有点矛盾。试着想一下sizeof这样的结构会是什么样的。