繁体   English   中英

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

[英]Trying to declare an array of struct room inside of the room struct definition 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;
};

我正在创建相互连接的房间的地图,我认为让每个房间跟踪与其相连的房间的最简单方法是制作一系列房间结构,然后将房间放入其中。

我收到一条错误消息,指出该房间的数组具有不完整的元素类型。 错误在“结构室连接[6];”行上

为了在内部存储struct ,它必须是指针类型。 否则,如注释中所述,此struct将占用无限空间。 下面的更改使它成为指向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;
};

我正在创建相互连接的房间的地图

你选择(具有一个阵列的解决方案rooms的结构内room )并不代表你的问题。 就像在一个room有其他rooms一样。 正如您的错误消息所示,这也不可能。

您需要在room结构中存储的是与其连接的其他rooms的链接(或地址)。 这样做是可行的,因为这是一个非常明确的问题,有明确的解决方案。 因此,在struct room ,将指针(即地址)存储到它所连接的房间。

struct room* connections[6]; 

上面的代码行表示connections是6个元素的数组,这些元素是指向struct room指针。

暂无
暂无

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

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