Indefinite-length array as member of struct: how?
Steve Summit
scs at adam.pika.mit.edu
Thu Jul 13 14:36:54 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);
In article <12574 at bloom-beacon.MIT.EDU> I wrote:
>This is unnecessarily baroque, and no more guaranteed to work
>than the original attempt at simulating a "dynamically sized
>structure."
I was hasty in my judgement. In the absence of a new definition
of struct node, I assumed that Phil was overlaying the string
field in some tricky way. In fact, given
struct node {
struct node* next;
*char string;
} *nodeptr;
the space allocated for the contents of the string has nothing
to do with the structure, and the effect (the resultant level of
indirection) is almost as if two separate mallocs had been done,
except of course that only one call is required. This is a fine
technique, and I should not have criticized it.
(If I had thought about it, I would have realized that Phil's
last line implied that his string field was declared differently
than the original char string[some_indeterminate_size], because
as we all know a char string[] could not have been assigned to.)
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);
but this is not a real complaint.
Steve Summit
scs at adam.pika.mit.edu
More information about the Comp.lang.c
mailing list