Zero Length Arrays Allowed in C Standard?

T. William Wells bill at twwells.com
Thu Dec 7 23:55:44 AEST 1989


In article <4733 at solo11.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
: In article <1989Dec5.112553.24087 at twwells.com>
: bill at twwells.com (T. William Wells) writes:
: \...
: \Consider a symbol table that is used to store strings. You could
: \declare a member of it as:
: \
: \     typedef struct SYMTAB {
: \             struct SYMTAB *sym_next;
: \             int     sym_type;
: \             char    *sym_text;
: \     } SYMTAB;
: \
: \This has the drawback that one needs two allocates for the
: \structure [...]
:
: symtabptr = (SYMTAB *) malloc(sizeof(SYMTAB) + strlen(text) + 1);
: symtabptr->sym_text = (char *) symtabptr + sizeof(SYMTAB);
: strcpy(symtabptr->sym_text, text);

I suppose so. A strict reading of the standard does not permit
this; it says that the result of malloc can be cast to *an*
object. I can imagine a debugging interpreter that says that, once
the result of malloc is cast, that's it. That could make
maintaining type information much easier and maybe eliminate
certain kinds of bugs. Another possibility is a capability machine
might do something esoteric.

On the other hand, the following code would work, even in those
environments:

	char    *dummyp;

	dummyp = (char *)malloc(sizeof(SYMTAB) + strlen(text) + 1);
	symtabptr = (SYMTAB *)dummyp;
	symtabptr->sym_text = dummyp + sizeof(SYMTAB);
	strcpy(symtabptr->sym_text, text);

But there is still that pointer going to waste.

---
Bill                    { uunet | novavax | ankh | sunvice } !twwells!bill
bill at twwells.com



More information about the Comp.lang.c mailing list