2015-01-12 138 views
1

我的代碼:指針在typedef的結構

typedef struct foo *bar; 

struct foo { 
    int stuff 
    char moreStuff; 
} 

爲什麼下面舉一個incompatible pointer type錯誤?

foo Foo; 
bar Bar = &Foo; 

據我所知,bar應該被定義爲一個指向foo,不是嗎?

+4

您的examlple沒有類型'foo',所以'富Foo'不應該編譯。你在'struct'定義中也缺少一個semicolin。你是否願意發佈代碼來真正重現你要求幫助你的錯誤? –

+0

哦,我很愚蠢。我想從我的結構中創建一個類型,現在修復。 – user102478

回答

2

完整的代碼應該看起來像

typedef struct foo *bar; 

typedef struct foo { //notice the change 
    int stuff; 
    char moreStuff; 
}foo; 

和使用

foo Foo; 
bar Bar = &Foo; 

,而不必struct foo typedef的,你的代碼將無法編譯。

另外,考慮到;結構後定義[後int stuff,但我認爲更是一個錯字的。

+1

@AlterMann絕對。錯過了那一個。謝謝 :-) –

0

更改這樣的代碼。

typedef struct foo *bar; 

struct foo { 
    int stuff; 
    char moreStuff; 
}; 

struct foo Foo; 
bar Bar = &Foo; 

否則,您可以使用該結構的typedef。

typedef struct foo { 
    int stuff; 
    char moreStuff; 
}foo; 

foo Foo; 
bar Bar=&Foo; 
1

這是應該的:

typedef struct foo *bar; 

struct foo { 
    int stuff; 
    char moreStuff; 
}; 


int main() 
{ 
    struct foo Foo; 
    bar Bar = &Foo; 

    return 0; 
} 
0
this code is very obfuscated/ cluttered with unnecessary, undesirable elements. 

In all cases, code should be written to be clear to the human reader. 
this includes: 
-- not making instances of objects by just changing the capitalization. 
-- not renaming objects for no purpose 

suggest: 

struct foo 
{ 
    int stuff; 
    char moreStuff; 
}; 

struct foo myFoo; 
struct foo * pMyFoo = &myFoo; 

which, amongst other things, actually compiles