C: the variable has an initializer, but an incomplete type

Trying to plunge into the old C. language. Currently on structures and getting this error:

"variable 'item1' has initializer but incomplete type"

Here is my code:

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);
}

I assumed that the structure definition was in the wrong place, so I moved it to the beginning of the file and recompiled, but I still get the same error. Where is my mistake?

+5
source share
3 answers

Get rid of structup item, you printed it.

+16
source

typedef struct { ... } itemcreates an unnamed type struct, and then typedefits name item. Thus, no struct item- just itemand unnamed type struct.

struct item { ... }, struct item item1 = { ... } item item1 = { ... }. , .

+9

,

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

does not declare a type name struct item, only item. If you want to use both names, use

typedef struct item { /* ... */ } item;
+4
source

All Articles