Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!ucsd!usc!bloom-beacon!adam.pika.mit.edu!scs From: scs@adam.pika.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct: how? Keywords: char string [] [0] [1] Message-ID: <12642@bloom-beacon.MIT.EDU> Date: 13 Jul 89 04:36:54 GMT References: <7360@c3pe.UUCP> <321@yetti.UUCP> <661@kl-cs.UUCP> <12574@bloom-beacon.MIT.EDU> Sender: daemon@bloom-beacon.MIT.EDU Reply-To: scs@adam.pika.mit.edu (Steve Summit) Lines: 44 In article <661@kl-cs.UUCP> pc@cs.keele.ac.uk (Phil Cornes) writes: >...dynamically sized structures are not supported in C >and your solution to the problem won't work. Here is a piece of code you might >try instead (when you include error checking): > nodeptr = (struct node *) malloc (sizeof(struct node)+strlen(data)+1); > strcpy ((char *)nodeptr+sizeof(struct node),data); > nodeptr->string = (char *)nodeptr+sizeof(struct node); In article <12574@bloom-beacon.MIT.EDU> I wrote: >This is unnecessarily baroque, and no more guaranteed to work >than the original attempt at simulating a "dynamically sized >structure." I was hasty in my judgement. In the absence of a new definition of struct node, I assumed that Phil was overlaying the string field in some tricky way. In fact, given struct node { struct node* next; *char string; } *nodeptr; the space allocated for the contents of the string has nothing to do with the structure, and the effect (the resultant level of indirection) is almost as if two separate mallocs had been done, except of course that only one call is required. This is a fine technique, and I should not have criticized it. (If I had thought about it, I would have realized that Phil's last line implied that his string field was declared differently than the original char string[some_indeterminate_size], because as we all know a char string[] could not have been assigned to.) It might (and I mean might; I'm not sure) be slightly clearer to rearrange it as nodeptr = (struct node *)malloc(sizeof(struct node)+strlen(data)+1); nodeptr->string = (char *)nodeptr+sizeof(struct node); strcpy(nodeptr->string, data); but this is not a real complaint. Steve Summit scs@adam.pika.mit.edu