简体   繁体   English

两个互相包含的结构

[英]two structs containing each other

I have this code: 我有以下代码:

typedef struct
{
    node* dest;
} edge;

typedef struct
{
    char *name;
    int visited;
    edge* edges[MAX_E];
} node;

So now struct edge have node* , and struct node have edge* , any one can explain to me how this work? 因此,现在struct edge具有node* ,而struct node具有edge* ,谁能向我解释这是如何工作的?

You need to declare (not define) one of the structs first 您需要先声明(不定义)其中一个结构

struct edge; // declare struct

struct node {
    char *name;
    int visited;
    struct edge *edges[MAX_E]; // array pf pointers
};
struct edge {
    struct node *dest;
};

Of course you can use typedef here. 当然,您可以在此处使用typedef But I fail to see any advantage in using it, so my code stays clear of typedef . 但是我看不到使用它的任何优势,因此我的代码没有使用typedef

I prefer to do it this way: 我更喜欢这样:

typedef struct node_s node;
typedef struct edge_s edge;

struct edge_s
{
    node   *dest;
};

struct node_s
{
    char   *name;
    int     visited;
    edge   *edges[MAX_E];
};

That way you can use the typedef names everywhere. 这样,您可以在任何地方使用typedef名称。

Note that neither struct contains an instance of the other. 注意,两个struct都不包含另一个的实例。 Instead, they each contain pointers to the other. 相反,它们每个都包含指向另一个的指针。 So the dependency is just a matter of being able to access pointers to the types before they've been defined. 因此,依赖关系只是能够在定义类型之前访问类型的指针。

Well, it's can't compile rigth away due to cross-definition of the structure. 好吧,由于结构的交叉定义,它无法完全编译。 You can fix that by adding the definition of the second structure before the first (like an opaque structure). 您可以通过在第二个结构的定义之前添加第二个结构的定义(如不透明结构)来解决此问题。

struct node;

Don't forgot to name your structure for that. 不要忘记为此命名您的结构。

After that, it will do exactly what it was coded for : edge->dest is a "node" pointer and "node" have an egde pointer array. 之后,它将完全按照其代码进行编码:edge-> dest是“节点”指针,“节点”具有egde指针数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM