Problem in defining object of a structure inside i

2019-07-16 05:02发布

问题:

This works:

struct LD__32
{
   struct LD__32 *ld;
};

But this doesn't:

struct LD_32
{
   struct LD_32 ld;
};

Why is this? I was compiling it as c++ code as pmg guessed. edited

回答1:

A structure in C cannot contain a member with incomplete type.

In the latter case you can't have LD_32 ld; defined inside the LD_32 definition because the struct LD_32 is not already defined at that point.

Check out constaints on structure in C

Section 6.7.2.1/2

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), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.



回答2:

Because it's a recursive and infinite definition. Think about it.



回答3:

Think about

sizeof(struct LD_32)


回答4:

struct LD_32
{
   LD_32 ld;
};

In this situation, how would you expect the compiler to determine the size of the struct LD_32.

Size of a struct is determined by calculating the sum of the size of all the members, plus some padding.

So even if there is no padding, the size of this struct LD_32 would be equal to size of it's member which is LD_32 itself, that means,

sizeof(LD_32) = size of member { size(LD_32) = size of member { size(LD_32) = size of member { size(LD_32) = ...    ... } } } } } } 

In short, the size cannot be calculated, because the size depends on itself which is unknown.

So the size is indeterminate.



标签: c struct