2013-09-24 180 views
0

我一直在網上關於創建一個結構,然後在main()中初始化它的教程。從我都跟着教程,我創建了我自己的例子,主要內容如下:C結構聲明和初始化

#include <stdio.h> 

struct test { 
    int num; 
}; 

main() { 
    test structure; 
} 

然而,這不起作用:

test.c: In function 'main': 
test.c:8: error: 'test' undeclared (first use in this function) 
test.c:8: error: (Each undeclared identifier is reported only once 
test.c:8: error: for each function it appears in.) 
test.c:8: error: expected ';' before 'structure' 

但是當我改變:

test structure; 

到:

struct test structure; 

的代碼編譯。這是爲什麼呢?從我看過的大量例子來看,似乎我不應該在'測試結構'之前需要'結構'。

感謝您的幫助/意見/答案。

+2

[typedef在結構聲明中需要]可能的重複(http://stackoverflow.com/questions/17124902/typedef-required-in-struct-declaration) –

+1

這些C教程或C++教程? – luiscubal

+0

我會說這是重複的。我的道歉,我試圖在發佈之前尋找答案,但我沒有在搜索中加入「typedef」這個詞,所以你發佈的鏈接沒有出現。謝謝。 –

回答

2

你讀的C++示例。在C中,你的結構類型是struct test而不是test

+0

謝謝!很快會接受你的答案作爲正確的答案(目前必須等待11分鐘)。 –

1

讓您可以通過做

typedef struct test_s 
{ 
    int num; 
} test;