Indefinite-length array as member of struct: how?
Phil Cornes
pc at cs.keele.ac.uk
Mon Jul 10 19:24:02 AEST 1989
>From article <7360 at c3pe.UUCP>, by charles at c3pe.UUCP (Charles Green):
> I have an application where I'm building and manipulating a stack of
> variable-length strings. I've set up a linked list of nodes, each one
> declared as follows:
>
> struct node {
> struct node* next;
> char string[];
> } *nodeptr;
>
> When I know how long the string is I'm pushing onto the stack, I say:
>
> nodeptr = malloc(strlen(data)+5);
> strcpy(nodeptr->string, data);
>
> The only problem I have is with compilation.....
This is not surprising, 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);
This solution will malloc() a block of memory large enough to hold a node
structure plus the space required to hold the data string and a terminating
null (line 1). Then the data bytes are copied into the tail end of that
block of memory (line 2). And finally the string pointer in the node
structure at the start of the block of memory is set to point to the string
itself (line 3).
Set up in this way the various components can be accessed as follows:
nodeptr - Is a pointer to the entire memory block
nodeptr->next - Will access this nodes link (next) pointer
nodeptr->string - Is a pointer to the start of the data array
nodeptr->string[n] - Will access the nth character in the data string
I hope this solves some of your problems.
Phil Cornes I just called to say .....
-----------*
JANET: cdtpc at uk.ac.stafpol.cr83
Phone: +44 (0)785 53511 x6058
Smail: Staffordshire Polytechnic, Computing Department
Blackheath Lane, STAFFORD, ST18 0AD, ENGLAND.
More information about the Comp.lang.c
mailing list