Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!usc!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: <661@kl-cs.UUCP> Date: 10 Jul 89 09:24:02 GMT References: <7360@c3pe.UUCP> Organization: University of Keele, England Lines: 48 From article <7360@c3pe.UUCP>, by charles@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@uk.ac.stafpol.cr83 Phone: +44 (0)785 53511 x6058 Smail: Staffordshire Polytechnic, Computing Department Blackheath Lane, STAFFORD, ST18 0AD, ENGLAND.