Indefinite-length array as member of struct: how?

RAMontante bobmon at iuvax.cs.indiana.edu
Thu Jul 13 23:42:35 AEST 1989


-In article <661 at kl-cs.UUCP> pc at 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);

scs at adam.pika.mit.edu (Steve Summit) <12642 at bloom-beacon.MIT.EDU> :
-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);


Don't these result in a chunk of memory that looks like:

        .-------------v---------------v--------------- - - - --.
        | ptr to next | ptr to string | "I AM A STRING . . . " |
        `-------------^---------------^--------------- - - - --'

where the second field (ptr to string) just points to the third?
I would think the desired memory chunk would look like:

        .-------------v--------------- - - - --.
        | ptr to next | "I AM A STRING . . . " |
        `-------------^--------------- - - - --'

In the first case, I access the string with "*(nodeptr->string)".  In
the second case I just use "nodeptr->string".

Go ahead and flame me.  I learn more from my failures than from my
successes...



More information about the Comp.lang.c mailing list