2012-07-17 65 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;