0

The following code is generating a compile error. I Do not understand why this is not working, could anyone explain why this is the case.

struct abc {
    int a;
    int b;
    struct abc var;
} a1;

int main()
{
    printf("%d",a1.a);
    return 0;
}

The above code is not working and returning error: error: field 'var' has incomplete type.

struct abc
{
    int a;
    int b;
    struct abc *var;
} a1;

int main()
{

    printf("%d",a1.a);
    return 0;
}
4

1 回答 1

6

A structure type is incomplete until its definition is completed with the terminating }. Your first example would have an infinite recursion of nested structures, which is probably not what you want. The second example simply contains a pointer to the structure, which is fine.

From the spec, 6.7.2.1 Structure and union specifiers, paragraph 3:

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself),

于 2013-10-17T06:02:47.960 回答