Indefinite-length array as member of struct: how?

William Davidsen davidsen at sungod.crd.ge.com
Tue Jul 11 05:56:53 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.  I've set up a linked list of nodes, each one
| declared as follows:
| 
| struct node {
| 	struct node* next;
| 	char	string[];
| } *nodeptr;
| 
| When I know how long the string is I'm pushing onto the stack, I say:
| 
| 	nodeptr = malloc(strlen(data)+5);

  You could change the string size to one, this would solve the problem
with compiler warnings. If it were my code I would use
"sizeof(nodeptr)+1" rather than 5, but I work on 16/32/64 bit machines
with a lot of my code.

  You could also make the string a char pointer and allocate the string
and node space, then set the string to point to the byte after the node
before copying the data in. This clearly imposed a performance penalty
(albeit tiny) but no longer relies on the string being last.

Here are a few passages from the draft standard (begin quote):

  Section 3.5.2.1 line 17:
	"as discussed in section 3.1.2.5, a structure is a type
consisting of a sequence of named members, whose storage is allocated in
an ordered sequence, and a union is a type consisting of a sequence of
named members, whose storage overlap."

  Section 3.1.2.5 line 21:
	"A *structure type* indicates a sequentially allocated set of
member objects, each of which has an optionally specified name and
possibly a distince type."

==== end quote ====

  Although I can't imagine anyone implementing this incorrectly,
neighther section says anything about "increasing" sequence, just that
the allocation is sequential. Still, how much better it would have been
to say something like:

	"A *structure type* indicates a set of member objects,
allocated in increasing sequential order, each of which has an
optionally specified name and possibly a distince type."

  I just have to feel that any wording which is less ambiguous is better.
	bill davidsen		(davidsen at crdos1.crd.GE.COM)
  {uunet | philabs}!crdgw1!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me



More information about the Comp.lang.c mailing list