Indefinite-length array as member of struct: how?
Bill Svirsky
svirsky at ttidca.TTI.COM
Thu Jul 20 04:19:11 AEST 1989
In article <669 at kl-cs.UUCP> pc at 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 at ttidca.tti.com | ...!{csun,psivax,rdlvax,retix}!ttidca!svirsky
More information about the Comp.lang.c
mailing list