2017-05-12 28 views
-3

如何使用C連接頭中的多重結構?如何使用C連接頭中的多結構?

的main.c:

#include <stdio.h> 
#include "main.h"  
int main() 
{ 
    printf("Hello, World!"); 
    return 0; 
} 

main.h:

struct Mother; 
struct Sub; 
///////////////////////////// 
struct Mother{ 
    sub item; 
}; 
struct Sub{ 
    mother item; 
}; 
///////////////////////////// 
typedef struct Mother mother; 
typedef struct Sub sub; 

$ gcc的-O3 -o輸出的main.c

In file included from main.c:2:0: 
main.h:5:2: error: unknown type name ‘sub’ 
    sub item; 
    ^~~ 
main.h:8:2: error: unknown type name ‘mother’ 
    mother item; 
    ^~~~~~ 

如何解決問題和'struct mother'和'struct Sub'的錯誤?


新的更新: 我也嘗試作爲標題:

struct Mother; 
struct Sub; 
///////////////////////////// 
struct Mother{ 
    Sub *item; 
}; 
struct Sub{ 
    Mother *item; 
}; 
///////////////////////////// 
typedef struct Mother Mother; 
typedef struct Sub Sub; 

而且錯誤。

+1

你的第一個proble是一個語法問題:'結構Mother'並不神奇'mother'請注意'struct'關鍵字和區分大小寫。你的第二個問題是一個空間問題:你不能把母親分成小孩,然後分給母親。爲此使用指向這些結構的指針。 –

+0

不錯,可以提交一個像我的代碼沒有問題的示例代碼? –

+0

@CPerfomance查看我的答案。你必須移動'typedef's。 – Marievi

回答

1

首先,你struct S的聲明之前寫你typedef秒。現在,你在typedef之前參考mothersub,因此預計會出現錯誤。

2。然後,而不是宣佈在struct Sub,反之亦然struct Mother,聲明指針struct,像這樣:

struct Mother; 
struct Sub; 

typedef struct Mother mother; 
typedef struct Sub sub; 

struct Mother{ 
    sub *item; 
}; 
struct Sub{ 
    mother *item; 
}; 
0

對不起隊友,你不能這樣做。

爲什麼你需要一個母親如果您母親已經有一個進入?

試想一下:

Mother A; 
Sub B; 

A.item = B; 
B.item = A; 

所以,你可以像這樣由A獲得B:

B.A; 

,您可以用B這樣的訪問:

A.B; 

所以你可以做這樣的連鎖:

A.B.A.B.A.B //and so on ... 

有可能的方式來編譯代碼,但我想在這裏向您展示的悖論,沒有一點要做到這一點

如果需要,你可以這樣做:

struct Sub 
{ 
    int motherId; //this refer to the Mother.Id;  
}; 

struct Mother 
{ 
    int id; //Stocked in Sub struct     
    struct Sub subs;// if needed you can do an array 
}; 

typedef struct Mother mother; 
typedef struct Sub sub; 

(這將編譯)