4 回答
In your code,
struct i {
int c;
};
there is no member variable of type struct i
neither it qualifies for anonymous structure Note. If you create a variable of that type, you'll be able to access the member variable c
, similar to what you've done for struct i3
with intern3
variable.
Adding a bit regarding the error message you're seeing,
struct s
has no member namedc
because, in case of an anonymous structure, the members are considered a direct member of the containing structure. In case of a struct
definition with a tag, that structure is not an anonymous structure and the member of the structure needs a structure variable of that type to be accessed.
NOTE:
Regarding anonymous structure, quoting C11
, chapter §6.7.2.1, (emphasis mine)
An unnamed member whose type specifier is a structure specifier with no tag is called an anonymous structure; an unnamed member whose type specifier is a union specifier with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.
From the gcc docs:
As permitted by ISO C11 and for compatibility with other compilers, GCC allows you to define a structure or union that contains, as fields, structures and unions without names. For example:
struct {
int a;
union {
int b;
float c;
};
int d;
} foo;
In this example, you are able to access members of the unnamed union with code like ‘foo.b’.
You were able to get at mystruct.a
because the structure had no tag. You can't get at your mystruct.c
because the containing struct for c
has the tag i
.
Change:
struct i {
int c;
};
to
struct {
int c;
}
and you should be able to get at mystruct.c
.
Member c
is declared inside inside strut i
. And you are not creating any variable for struct i
.
So, you can't access member c
.
When you mention mystruct.c
, it expects c
to be a member of structure s
, which is not.
If you don't name your dog, you can't call it
That is exactly what unnamed says - it has no name, so you cannot access it by name.
The only reason to have unnamed members in a structure is if you are mirroring a structure given externally, and you don't care about specific pieces of it, so you name only the pieces you want to access.