Indefinite-length array as member of struct: how?

David Gelhar davidg at eleazar.dartmouth.edu
Mon Jul 10 06:02:02 AEST 1989


>In article <7360 at c3pe.UUCP> charles at c3pe.UUCP (Charles Green) writes:
>>I have an application where I'm building and manipulating a stack of
>>variable-length strings.  [...]
>>
>>struct node {
>>	struct node* next;
>>	char	string[];
>>} *nodeptr;
>>

In article <8870 at venera.isi.edu> lmiller at venera.isi.edu.UUCP (Larry Miller) writes:

>[...]
>
>	2)  This works because of a trick: the order in which fields in the
>	structure are declared.  Simply changing the definition of a struct node
>	to:
>		struct node {
>			char	string[];
>			struct node* next;
>		};
>	causes disaster.
>
>	3)  Because of the indeterminate length of the string field in each
>	node, you can't pass a struct node to/from a function.  All that gets
>	copied over will be the next field and, at best, one character from 
>	the string field.
>[...]

2) Isn't a very strong argument.  K & R specifies that addresses are
assigned in increasing order from left to right; as long as you
DON'T change the definition order, disaster is avoided.  The danger
isn't that the compiler will do the wrong thing, rather that some
later (and lesser :-)) programmer will not understand the
significance of the ordering of the structure members.  Situations
like this are an excellent opportunity to try out a seldom-used
feature of C -- the "comment".

The obvious answer to 3) is to simply pass the address of the
structure instead of the structure itself.  Admittedly, this could
be a limitation, but copying structures for a function call is
expensive, so maybe you didn't want to do that anyway. :-)

This is certainly a trick, and not one I'd use every day, but it
could have its uses.  For one thing, it requires only one malloc per
element, while more straightforward methods (like putting a char *
in the struct) require two.  Depending on the malloc overhead (in
terms of both internal fragmentation and execution time), it seems
this could be a useful approach.



More information about the Comp.lang.c mailing list