Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!usc!apple!ames!ncar!noao!arizona!sunquest!ggg From: ggg@sunquest.UUCP (Guy Greenwald) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct: how? Summary: Try two malloc calls for greater simplicity Keywords: char string [] [0] [1] Message-ID: <171@sunquest.UUCP> Date: 11 Jul 89 20:00:33 GMT References: <7360@c3pe.UUCP> <321@yetti.UUCP> <661@kl-cs.UUCP> <12574@bloom-beacon.MIT.EDU> Organization: Sunquest Information Systems, Tucson Lines: 44 In article <12574@bloom-beacon.MIT.EDU>, scs@adam.pika.mit.edu (Steve Summit) writes (in part): > > #define INITIALALLOC 1 > > struct node { > struct node* next; > char string[INITIALALLOC]; > } *nodeptr; > > nodeptr = (struct node *)malloc(sizeof(struct node) + > strlen(data) - INITIALALLOC + 1); /* + 1 for \0 */ > (void)strcpy(nodeptr->string, data); > > The only real difference here is the use of sizeof (which many > others have suggested) and the macro INITIALALLOC which obviates > the need for a 0-sized array while documenting and coordinating > the adjustment required when allocating. The continuing discussion on the problem of dynamically allocating memory for a structure of the nature: struct node { struct node *next; char *string; /* Instead of char string[], which * started the whole fuss */ ... } *nodeptr; seems to have ignored the possibility of two malloc() calls, one for the node, another for the string. nodeptr = (struct node *) malloc(sizeof(*nodeptr)); /* After the length of char data[] is known: */ nodeptr->string = (char *) malloc(strlen(data) + 1); (void) strcpy(nodeptr->string, data); Perhaps this isn't as much fun as fooling the compiler with char string[THINGAMAJIG], but it is straightforward, easy to understand and (I think) more flexible. Slings and arrows, anyone? --G. Guy Greenwald II