2012-07-17 69 views
5

試圖讓我周圍的舊的C語言頭。目前在結構和收到此錯誤:C:變量初始化,但不完全類型

"variable 'item1' has initializer but incomplete type" 

這裏是我的代碼:

typedef struct 
{ 
    int id; 
    char name[20]; 
    float rate; 
    int quantity; 
} item; 

void structsTest(void); 

int main() 
{ 
    structsTest(); 

    system("PAUSE"); 
    return 0; 
} 

void structsTest(void) 
{ 
    struct item item1 = { 1, "Item 1", 345.99, 3 }; 
    struct item item2 = { 2, "Item 2", 35.99, 12 }; 
    struct item item3 = { 3, "Item 3", 5.99, 7 }; 

    float total = (item1.quantity * item1.rate) + (item2.quantity * item2.rate) + (item3.quantity * item3.rate); 
    printf("%f", total); 
} 

我猜也許是結構確定指標是在錯誤的位置,所以我把它移動到文件並重新編譯的頂部,但我仍然遇到同樣的錯誤。我的錯誤在哪裏?

回答

16

獲取item前擺脫struct,你已經typedef定義它。

9

typedef struct { ... } item創建一個未命名的struct類型,然後typedef將其命名爲item。因此,有沒有struct item - 只是item和無名struct類型。

請使用struct item { ... },或將您所有的struct item item1 = { ... } s更改爲item item1 = { ... }。你做哪一件取決於你的偏好。

4

的問題是,

typedef struct { /* ... */ } item; 

沒有聲明類型名稱struct item,只有item。如果你希望能夠使用這兩個名稱使用

typedef struct item { /* ... */ } item;