Indefinite-length array as member of struct; sizeof(char)
Ari Halberstadt
ari at eleazar.dartmouth.edu
Wed Jul 19 02:53:04 AEST 1989
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 at fozzy.UUCP> ellis at fozzy.UUCP (Randy Ellis) writes:
>In article <7360 at c3pe.UUCP>, charles at 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"
More information about the Comp.lang.c
mailing list