Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: variable has initializer but incomplete type

Tags:

c

struct

Trying to get my head around the old C language. Currently on structs and getting this error:

"variable 'item1' has initializer but incomplete type"

Here's 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 guessed perhaps the struct defintion was in the wrong location so I moved it to the top of the file and recompiled, but I am still getting the same error. Where's my mistake?

like image 859
Matt Avatar asked Jul 17 '12 02:07

Matt


3 Answers

Get rid of struct before item, you've typedef'd it.

like image 192
Keith Nicholas Avatar answered Oct 21 '22 14:10

Keith Nicholas


The problem is that

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

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

typedef struct item { /* ... */ } item;
like image 39
Geoff Reedy Avatar answered Oct 21 '22 15:10

Geoff Reedy


typedef struct { ... } item creates an unnamed struct type, then typedefs it to the name item. So there is no struct item - just item and an unnamed struct type.

Either use struct item { ... }, or change all your struct item item1 = { ... }s to item item1 = { ... }. Which one you do depends on your preference.

like image 10
Chris Lutz Avatar answered Oct 21 '22 14:10

Chris Lutz