lyrx said:
Basically what I want to do is to replace the 64K buffer in the union
with something less, like 2K. Then if I want more space I reallocate.
This is FreeBSD code in gethostby(name/addr). The union is either
allocated on the stack, or can be dynamically allocated, but in both
cases 64K memory is needed. I want to work around this.
I just wanted to ensure that
union x {
struct y;
char z[2*1024];
}
can be replaced by:
union x {
struct y;
char z[1];
}
union x *p = malloc(2*1024);
And I can access both p->y and p->z.
There happens to be enough information in your latest post that we can
understand what you're saying, but in general you should provide some
context from the previous article in each followup, enough so that the
followup is comprehensible by itself. Don't assume that we can see
the article to which you're replying. See this article, or most of
the followups posted here, for examples of what it should look like.
Google Groups makes it unnecessarily difficult to do this properly,
and far too easy to do it improperly. Fortunately, there's a
workaround:
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
And please complain to Google about their broken interface.
Getting back to your actual question, the "struct y;" declaration is
invalid; I'll assume you meant something like "struct foo y;", where
"struct foo" is the type name and "y" is the name of a member of that
type.
What you're trying to do is very similar to the "struct hack",
described in question 2.6 of the comp.lang.c FAQ (google "c FAQ").
The struct hack works with structures rather than unions; it's very
likely to work, although Dennis Ritchie has called it "unwarranted
chumminess with the C implementation".
C99 adds "flexible array members", basically a supported version of
the struct hack with a different syntax:
struct s {
size_t len;
char buf[];
};
but this applies only to structs, not to unions.
What you're trying to do will *probably* work, but it's not guaranteed
by the standard. Use it at your own risk.