2014-02-19 124 views
0

我正在開發一個簡單的程序,根據地圖在房子中創建房間。對於每個房間,我列出連通房間。事情是,這不能編譯。任何想法爲什麼?在結構中聲明結構?

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

@unwind它是相似的,但不完全相同 - 這裏只有1個結構。 – Dukeling

回答

4

更換

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

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

解釋問題的原因要好得多,而不僅僅是解決問題。 – Dukeling

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; 
    
1

不能使用結構類型t_room,因爲它沒有定義來定義類型t_room本身。因此,你應該和實際定義struct s_room之前

struct s_room *connect; 

或者你可以typedefstruct s_room型替換此

t_room *connect; 

。然後你可以在定義中使用類型別名。

// 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!這看起來像名稱空間混亂,沒有任何實際的好處。