I have three structs that share the first type and name of the first field:
struct TYPEA {
char *name;
int x,y; /*or whatever*/
};
struct TYPEB {
char *name;
float a[30]; /*or whatever*/
};
struct TYPEC {
char *name;
void *w,*z; /*or whatever*/
};
If I remember correctly the first field of a struct is required to start at the same address as the struct itself.
This makes me wonder if the same holds for a union:
union data {
struct TYPEA;
struct TYPEB;
struct TYPEC;
};
union data *p = function_returning_a_sane_default_for_union_data();
printf("%s", (char*) p);
I have 2 question regarding this:
- are unions required by standard to always have their content at the same address?
- would it work if the structs all had the same fiels, so differing only in name?
The first element of a
struct
orunion
is guaranteed to have the same address-value as thestruct´/
union itself. Apparently it has not the same type!For your usage, you do not need the cast and actually should avoid it:
So you could (see below) simply
(Note: that your usage of unnamed
union
members is not standard compilant. It is a (very useful) gcc extension (-fms-extensions
, at least also supported by MSVC, too).)But: The code in your question is wrong. You have to name each union member or have the type declarator with each member. With the same first member, It will not weork, though, because the names of the mebers of such unnamed members have to be unique (how else are they supposed to be accesseed individually?). So this will not really work. What you could do is:
and
even if the
struct
contains a value ofTYPEB
currently.An alternative and more clear way, would be to wrap the
union
into astruct
:This also uses the gcc extension at two levels: for the outer
struct
and theunion
. As such, it requires unique names for all possible paths. If you want to be 100% compliant, name each member like above and use the full path on access.Note: I removed the
name
member from the innerstruct
s in theunion
and moved it to the outerstruct
. I also changed names. The only well accepted naming convention in C is to use all-uppercase for macros only.