簡體   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