简体   繁体   English

试图在C的房间结构定义中声明一个结构房间数组

[英]Trying to declare an array of struct room inside of the room struct definition in C

Is it impossible to do something like this in C? 用C做这样的事情是不可能的吗?

struct room{
        //Name of the room
        char* name;
        //Type fo the room
        char* type;
        //Array of outbound connections, max of six
        struct room connections[6];
        //A counter variable for how many connections the room actually has been assigned
        int numOfConnections;
};

I am creating a map of rooms which are connected to each other, and I thought the easiest way for each room to keep track of the rooms it is connected to would be to make an array of room structs and then put the rooms in their. 我正在创建相互连接的房间的地图,我认为让每个房间跟踪与其相连的房间的最简单方法是制作一系列房间结构,然后将房间放入其中。

I am getting an error that says room the array has an incomplete element type. 我收到一条错误消息,指出该房间的数组具有不完整的元素类型。 The error is on the line "struct room connections[6];" 错误在“结构室连接[6];”行上

In order to store a struct inside itself, it must be of pointer type. 为了在内部存储struct ,它必须是指针类型。 Otherwise, as mentioned in comments, this struct would take infinite space. 否则,如注释中所述,此struct将占用无限空间。 The change below makes it into a pointer to 6 struct room 's. 下面的更改使它成为指向6个struct room的指针。

struct room{
        //Name of the room
        char* name;
        //Type fo the room
        char* type;
        //Array of outbound connections, max of six
        struct room* connections[6];
        //A counter variable for how many connections the room actually has been assigned
        int numOfConnections;
};

I am creating a map of rooms which are connected to each other 我正在创建相互连接的房间的地图

The solution you have chosen (of having an array of rooms within a structure of room ) does not represent your problem. 你选择(具有一个阵列的解决方案rooms的结构内room )并不代表你的问题。 That is like having other rooms within a room . 就像在一个room有其他rooms一样。 And this is not possible to do either as your error message shows. 正如您的错误消息所示,这也不可能。

What you need to store within a structure of room are the links (or addresses) of the other rooms it is connected to. 您需要在room结构中存储的是与其连接的其他rooms的链接(或地址)。 Doing this is possible as it is a very well defined problem with a clear solution. 这样做是可行的,因为这是一个非常明确的问题,有明确的解决方案。 So in the struct room you store the pointers (which are addresses) to the rooms it is connected to. 因此,在struct room ,将指针(即地址)存储到它所连接的房间。

struct room* connections[6]; 

The above line of code means that connections is an array of 6 elements which are pointers to the struct room . 上面的代码行表示connections是6个元素的数组,这些元素是指向struct room指针。

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

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