2016-12-03 108 views
1

我已经看到过有关指向对方的结构的问题,我尝试了很多东西,但是我无法解决我的问题。我的大脑正在燃烧!互相引用的结构

我有两个不同的结构/类型:set_tnode_t

#ifndef _SETH_ 
#define _SETH_  
#include "node.h" 
#include "list.h" 

typedef struct { 
    list_t* list; 

}set_t; 

set_t* createSet(node_t*); 
set_t* findSet(node_t*); 
set_t* unionSet(node_t*, node_t*); 

#endif 

我没有在我的set_t结构的任何node_t,但我用node_t作为参数,所以我包括node.h,你可以看到。列表是一个链接的节点列表,但目前这与我的问题没有关系。

#ifndef _NODEH_  
#define _NODEH_ 

//?? #include "set.h" 
typedef struct set_t s; 

typedef struct node_t{ 
    int color; 
    int dist; 
    int key; 
    int date; 
    int end; 
    s* set; 
    struct node_t* father; 
}node_t; 

node_t* createNode(int); 
#endif 

在beggining,我使用包括node.h set.h,因为我在我的节点结构使用一组。但是我对这些包含了一些“循环”。 所以I'im尝试使用此指令:

typedef struct set_t s; 

,以避免这个循环的问题。

但是,这一次我有一个问题/警告,我想我明白: 当我这样做(让我们假设我们有一个node_t * N):

set_t* s = (set_t*)malloc(sizeof(set_t)); 
    n->set= s; 

我有不兼容的一个assignement指针类型的警告,也许是因为s是一个set_t *,但n->设置为* ...

我在做什么错?我真的想知道这是如何工作的,当你想在xh中包括xh在yh和yh中时... 同样的事情,如果yh需要xh,zh需要yh,而xh需要zh .. 我真的很希望我足够清楚为你们帮助我。

+3

http://stackoverflow.com/questions/888386/resolve-circular-typedef-dependency。不要投入malloc返回。 'void *'做这项工作。不要键入一个结构两次。只在一个标题中进行。 – Stargateur

回答

1

编译器将类型s看作与set_t类型不同的东西。

为了对准这样做到以下几点:

在set.h变化

typedef struct { 
    list_t * list; 
} set_t; 

typedef struct Set { 
    list_t* list; 
} set_t; 

在node.h变化

typedef struct set_t s; 

typedef struct Set set_t; // True forward declaration of set_t. 

s * set; 

set_t * set; 

更新:

删除所有那些没用的typedef可能使事情变得更清晰。您的代码将如下所示:

集。ħ

#ifndef _SETH_ 
#define _SETH_ 

#include "node.h" 
#include "list.h" 

// define type "struct Set" 
struct Set { 
    struct List * list; // defintion of struct List to be adjusted in list.h 
}; 

struct Set * createSet(struct Node*); 
struct Set * findSet(struct Node*); 
struct Set * unionSet(struct Node*, struct Node*); 


#endif 

node.h

#ifndef _NODEH_  
#define _NODEH_ 

// declare forward type "struct Set" 
struct Set; 

// define type "struct Node" 
struct Node { 
    int color; 
    int dist; 
    int key; 
    int date; 
    int end; 
    struct Set * set; 
    struct Node* father; 
}; 

struct Node * createNode(int); 


#endif 
+0

非常感谢你的时间,如果你有更多时间给我,我还有一个问题,我们到底做了什么?我们是重新命名结构还是其他什么?当我们做typedef结构集{list} {list * list_t * } set_t;什么是“Set”?什么是“set_t”? –

+1

'struct set'是一个* named * struct数据类型。使用'typedef'你可以在另一个名字空间中为同一个事物创建另一个类型。事实上,你会让事情变得复杂,并且像往常一样,当事情复杂化时,会增加误解的可能性,这是你遇到的问题之一。 @MonsieurOurer – alk

+0

好的,现在对我来说很清楚,非常感谢你的帮助:) –