Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!purdue!bu-cs!dartvax!eleazar.dartmouth.edu!ari From: ari@eleazar.dartmouth.edu (Ari Halberstadt) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct; sizeof(char) Summary: Missing type cast and a question Keywords: char string [] [0] [1] Message-ID: <14474@dartvax.Dartmouth.EDU> Date: 18 Jul 89 16:53:04 GMT References: <7360@c3pe.UUCP> <821@fozzy.UUCP> Sender: news@dartvax.Dartmouth.EDU Reply-To: ari@eleazar.dartmouth.edu (Ari Halberstadt) Organization: Dartmouth College, Hanover, NH Lines: 34 I sent the following article, but it seems to have arrived without its body [probably would have forgotten its head if it wasn't attached :-)]. I'm still new to the news networks, so I hope it doesn't appear twice. The article follows: In article <821@fozzy.UUCP> ellis@fozzy.UUCP (Randy Ellis) writes: >In article <7360@c3pe.UUCP>, charles@c3pe.UUCP (Charles Green) writes: >> When I know how long the string is I'm pushing onto the stack, I say: >> nodeptr = malloc(strlen(data)+5); >> to cover the struct node* and terminating NULL, and then simply >> strcpy(nodeptr->string, data); > >Does this fit your needs? Change string into a char pointer, then allocate >dynamic memory for the string and save the pointer into nodeptr->string. > nodeptr = malloc(sizeof(struct node)); > nodeptr->string = malloc(strlen(data)+1); > strcpy(nodeptr->string,data); The sollution given by Randy Ellis is incomplete. Specifically, it omits a type cast from type "char *" to type "struct node *". The correct line should read: nodeptr = (struct node *) malloc(sizeof(struct node)); I also have a question about memory allocation. Are characters guaranteed to be only one memory address long? This is very important in expressions such as: nodeptr->string = malloc(strlen(data)+1); Should the above line really be written as: nodeptr->string = malloc( (strlen(data)+1) * sizeof(char) ); I have seen the latter in several books, but it really wasn't clear from the examples what should be done. If possible, please include a source (e.g., book name) with your response. Ari Halberstadt '91, "Long live short signatures"