Hill Pang
writes:
The is my code:
struct f1 {
int x; int y[];
} f1 = { 1, { 2, 3, 4 } };
void main()
This should be "int main(void)".
{
printf("sizeof %d\n", sizeof f1);
}
The output(by GCC) is 4.
My question is why it doesn't count the size of the flexible array
while it is static initialized? In other words, if I want to know the
*really* size of f1, how to do it? is it possible?
Because that's the way it's defined by the language.
N1570 6.7.2.1p18:
As a special case, the last element of a structure with more
than one named member may have an incomplete array type; this is
called a flexible array member . In most situations, the flexible
array member is ignored. In particular, the size of the structure
is as if the flexible array member were omitted except that it
may have more trailing padding than the omission would imply.
Yes, it would be nice if sizeof yield the full size, including however
much space is in that final array. But that would require the compiler
to keep track of how it was allocated, and to generate run-time code
when the size is not constant. It also would have required nailing down
the definition in all cases.
Flexible array members are basically a better-defined version of the
"struct hack" (see question 2.6 of the comp.lang.c FAQ,
<
http://www.c-faq.com>).
If you want to keep track of how many elements are in that final array,
you'll just have to do it yourself. For example, you might add a member
that holds the current number of elements -- and make sure that its
value is correct at all times.
--
Keith Thompson (The_Other_Keith) (e-mail address removed) <
http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"