Zero Length Arrays Allowed in C Standard?

Leslie Mikesell les at chinet.chi.il.us
Fri Dec 8 03:02:20 AEST 1989


In article <7350 at quick.COM> srg at quick.COM (Spencer Garrett) writes:

>> already been posted.  Let me add that there are no logical
>> problems with the concept; all properties of such objects
>> would be well defined.
>> 	sizeof zero would be 0
>> 	&zero points at the object
>> 	++ptr_to_zero would still point to zero
>> 	*ptr_to_zero needn't do anything to "access" the contents
>> 	&zero_length_array[0] points one past the last valid element
>> etc.

>Just some minor nits so as not to confuse those who are still having
>trouble with this concept.

>	++ptr_to_zero   *will* increment the pointer.  The *array*
>has size 0.  Its *elements* do not.  There just aren't any *of*
>them.  Thus sizeof(zero) == 0,  sizeof(zero[0]) > 0, and
>(sizeof(zero)/sizeof(zero[0])) gives the number of elements in
>the array (as always) which in this case happens to be 0.

This sounds right to me. And you can't cheat by pretending that
sizeof(element) == 0.  Otherwise loops that detect the end of
an array by checking for an element address > address of last
element would never end.  Besides, when referencing an array
through a pointer (otherwise you can't ++an_address), there is
no notion of the size of the array being pointed to.

>	*ptr_to_zero   will access storage wherever the pointer
>points.  If that's beyond the end of the malloc'd storage it may
>bomb like any other array reference.  If the array was statically
>allocated, then this is always an illegal reference.

But it's up to the compiler to allocate array storage. Remember that
this was declared as "type name[0]"  (probably some symbol that
the preprocessor evaluates as 0, actually).  Thus the compiler can
make sure that the reference is legal.  However, because a reference
to array[end + 1] is also supposed to be legal, the address would have
to point at enough real memory to hold one element, although it could
be treated as a union with anything convenient.  Whether it is addressed
as name[0] or ptr=name; *ptr can't make any difference, and the
compiler can't know the size of the array being accessed via ptr.  To
make the concept useful, it would have to allow linking to code that
accesses arrays via pointers, so the compiler can't cheat and pretend
that there is a special type of element stored in arrays of 0 length.

>Actually, I must confess that structures with no members
>of nonzero size do cause some problems, but arrays of
>length zero make perfect sense, and that's the usage that
>started this discussion.

How about an array of 0 length of structures containing elements
of nonzero size?  Could you then sizeof(array[0].element) without 
having to create a real instance of the struct?

Les Mikesell
  les at chinet.chi.il.us



More information about the Comp.lang.c mailing list