Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!apple!sun-barr!cs.utexas.edu!uunet!mcvax!ukc!kl-cs!pc From: pc@cs.keele.ac.uk (Phil Cornes) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct: how? Message-ID: <669@kl-cs.UUCP> Date: 14 Jul 89 14:23:15 GMT References: <23282@iuvax.cs.indiana.edu> Organization: University of Keele, England Lines: 80 From article <23282@iuvax.cs.indiana.edu>, by bobmon@iuvax.cs.indiana.edu (RAMontante): > Go ahead and flame me. I learn more from my failures than from my > successes... 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); you end up with a memory layout as you suggest: .-------------v--------------- - - - --. | ptr to next | "I AM A STRING . . . " | `-------------^--------------- - - - --' In this case the expression: nodeptr1->string1 evaluates to a pointer constant to the first (and only declared) element of the string1 array. Accessing a single character in the stored data string (say the 'M') can be done as follows: nodeptr1->string1[3] 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); you end up with the memory laid out again as you suggest: .-------------v---------------v--------------- - - - --. | ptr to next | ptr to string | "I AM A STRING . . . " | `-------------^---------------^--------------- - - - --' These two may look very different but you will find that they don't behave so in programs. Once again, the expression: nodeptr2->string2 is a pointer to the first element of the string2 array. Accessing a single character in the stored data string (say the 'M') can be done as follows: nodeptr2->string2[3] As you can see this is the same as the first example. 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. So, no flames... you pays your money and you takes your choice!!! Phil Cornes I just called to say ..... -----------* JANET: cdtpc@uk.ac.stafpol.cr83 Phone: +44 (0)785 53511 x6058 Smail: Staffordshire Polytechnic, Computing Department Blackheath Lane, STAFFORD, ST18 0AD, ENGLAND.