Indefinite-length array as member of struct: how?

Guy Greenwald ggg at sunquest.UUCP
Wed Jul 12 06:00:33 AEST 1989


In article <12574 at bloom-beacon.MIT.EDU>, scs at adam.pika.mit.edu (Steve Summit) writes (in part):
> 
> 	#define INITIALALLOC 1
> 
> 	struct node {
> 		struct node* next;
> 		char string[INITIALALLOC];
> 	} *nodeptr;
> 
> 	nodeptr = (struct node *)malloc(sizeof(struct node) +
> 		strlen(data) - INITIALALLOC + 1);	/* + 1 for \0 */
> 	(void)strcpy(nodeptr->string, data);
> 
> The only real difference here is the use of sizeof (which many
> others have suggested) and the macro INITIALALLOC which obviates
> the need for a 0-sized array while documenting and coordinating
> the adjustment required when allocating.


The continuing discussion on the problem of dynamically allocating memory
for a structure of the nature:

	struct node {
		struct node *next;
		char *string;		/* Instead of char string[], which
					 * started the whole fuss */
		...
	} *nodeptr;

seems to have ignored the possibility of two malloc() calls, one for the
node, another for the string.

	nodeptr = (struct node *) malloc(sizeof(*nodeptr));
	/* After the length of char data[] is known: */
	nodeptr->string = (char *) malloc(strlen(data) + 1);
	(void) strcpy(nodeptr->string, data);

Perhaps this isn't as much fun as fooling the compiler with
char string[THINGAMAJIG], but it is straightforward, easy to understand
and (I think) more flexible.

Slings and arrows, anyone?

--G. Guy Greenwald II



More information about the Comp.lang.c mailing list