zero length array

msb at sq.UUCP msb at sq.UUCP
Fri Feb 20 04:44:33 AEST 1987


Dizio at udel.edu writes:
> Not to nit pick but is it always true that within the structure 
> 
>    struct LINE { struct header_junk hj; char text[32768]; } ;
> 
> 'text' falls immediately after 'hj'?

It isn't guaranteed.  A compiler is allowed to leave space in there
according to the type of the following member, i.e., char[] here.
However, any extra space required for alignment of the inner struct
will be counted as part of that struct.

It seems most unlikely that "char[]" could have alignment requirements
more strict than a struct, but there is nothing forbidding it.

>    Is the following a portable way of finding out where a field
> within a structure is located?
>     & (((struct any_struct_tag *) 0)->any_field)

No.  When 0 is converted to pointer type (remember, a cast is a conversion),
all you know is that the resulting pointer doesn't point to a valid object.
In this case there are certainly machines where it's not a numeric 0.

You need an actual object of the struct type, say tmp; and then, of course,
you can say:

	(char *) &tmp.any_field - (char *) &tmp

In the current ANSI draft, there is a predefined macro "offsetof" which
does something like this for you without needing you to specify an object.

However, I've never met a case where this operation was really necessary.
Usually the job can be done more comprehensibly with unions.

Mark Brader, utzoo!sq!msb			C unions never strike!



More information about the Comp.lang.c mailing list