在结构中声明一个结构?

时间:2014-02-19 11:33:48

标签: c data-structures

我正在开发一个简单的程序,根据地图在房子里创建房间。对于每个房间,我列出连通房间。问题是,这无法编译。知道为什么吗?

typedef struct s_room {
    char *name;
    int nbr;
    int x;
    int y;
    bool start;
    bool end;
    int ants;
    int current;
    t_room *connect;
    int visited;

} t_room;

我认为它来自t_room *connect,但我无法弄清楚如何解决这个问题。

3 个答案:

答案 0 :(得分:4)

替换

typedef struct      s_room
{
    ....
    t_room          *connect;
    ....
}                   t_room;

typedef struct      s_room
{
    ....
    struct s_room   *connect;
    ....
}                   t_room;

答案 1 :(得分:3)

两个选项:

  1. 类型

    的转发声明
    typedef struct      s_room t_room;
    struct s_room {
        t_room          *connect;
    };
    
  2. 使用struct s_room

    typedef struct s_room {
        struct s_room  *connect;
    } t_room;
    

答案 2 :(得分:1)

您不能使用结构类型t_room来定义类型t_room本身,因为它尚未定义。因此,您应该替换此

t_room *connect;

struct s_room *connect;

或者您可以在实际定义typedef之前输入struct s_room struct s_room。然后,您可以在定义中使用类型别名。

// struct s_room type is not defined yet.
// create an alias s_room_t for the type.

typedef struct s_room s_room_t; 

// define the struct s_room type and
// create yet another alias t_room for it.

typedef struct s_room {
    // other data members
    s_room_t *connect; 

    // note that type of connect is not yet defined
    // because struct s_room of which s_room_t is an alias
    // is not yet fully defined.

} t_room;

// s_room_t and t_room are both aliases for the type struct s_room

就个人而言,我更喜欢前者,因为要做后者,你必须引入一个额外的typedef来定义另一个typedef!这看起来像名称空间混乱,没有任何实际好处。