Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!philmtl!philabs!ttidca!svirsky From: svirsky@ttidca.TTI.COM (Bill Svirsky) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct: how? Message-ID: <4799@ttidca.TTI.COM> Date: 19 Jul 89 18:19:11 GMT References: <23282@iuvax.cs.indiana.edu> <669@kl-cs.UUCP> Reply-To: svirsky@ttidcc.tti.com (Bill Svirsky) Organization: Citicorp/TTI, Santa Monica Lines: 64 In article <669@kl-cs.UUCP> pc@cs.keele.ac.uk (Phil Cornes) writes: +With a structure declaration: + + struct node1 { + struct node1 *next1; + char string1[1]; + } *nodeptr1; + +and a block of code: + + nodeptr1=(struct node1 *)malloc(sizeof(struct node1)+strlen(data)); + (void)strcpy(nodeptr1-+string1,data); [stuff deleted] +On the other hand, with a structure declared as: + + struct node2 { + struct node2 *next2; + char *string2; + } nodeptr2; + +and a block of code like: + + nodeptr2=(struct node2 *)malloc(sizeof(struct node2)+strlen(data)+1); + nodeptr2-+string2 = (char *)nodeptr2+sizeof(struct node2); + (void)strcpy(nodeptr2-+string2,data); [more stuff deleted] + My own preference in +this case is to use the second of these solutions for two reasons: + +1. The first solution relies upon a lot more knowledge of the way that C + operates internally, in order to be confident that it will work. + +2. The first solution also suffers from the problem that it relies upon + accessing the string1 array outside its declared subscript range, + which must be classed as a 'tacky' practice at best. One more advantage to the 2nd solution is that it is easily expandable and very flexible. For instance, given: struct node { struct node *next; char *string1; char *string2; } nodeptr; use a block of code like: nodeptr=(struct node *)malloc(sizeof(struct node)+ strlen(data1)+strlen(data2)+2); nodeptr->string1 = (char *)nodeptr+sizeof(struct node); nodeptr->string2 = nodeptr->string1+strlen(data1)+1); (void)strcpy(nodeptr->string1,data1); (void)strcpy(nodeptr->string2,data2); -- Bill Svirsky, Citicorp+TTI, 3100 Ocean Park Blvd., Santa Monica, CA 90405 Work phone: 213-450-9111 x2597 svirsky@ttidca.tti.com | ...!{csun,psivax,rdlvax,retix}!ttidca!svirsky