Re: confused about copying strings
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Sun, 18 Jul 2010 00:11:59 +0100
Angus wrote:
The sample code below simulates receiving a protocol message with a tlv structure - type/length/data_value.
I am confused about copying the actual data to a temp string.
Since you know in advance that you have sufficient storage to store the copy, use strcpy.
int dtype = *mybytes++;
int dsize = *mybytes++;
size_t size = dsize;
char *data = malloc(size);
if(data != NULL)
{
if(strlen(mybytes) < size)
{
strcpy(data, mybytes);
printf("%s\n", data);
/* when finished with data... */
free(data);
}
else
{
something's wrong - your mybytes string length indicator is too low.
}
}
else
{
handle the out-of-memory error
}
data points to the /first/ character of the string - strcpy can't change data's value because we only passed its value, not the object itself. But strcpy can certainly copy the string to it.
<snip>
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
.
- Follow-Ups:
- Re: confused about copying strings
- From: Ian Collins
- Re: confused about copying strings
- References:
- confused about copying strings
- From: Angus
- confused about copying strings
- Prev by Date: confused about copying strings
- Next by Date: Re: confused about copying strings
- Previous by thread: confused about copying strings
- Next by thread: Re: confused about copying strings
- Index(es):
Relevant Pages
|