Archived

This topic is now archived and is closed to further replies.

GekkoCube

some scenarios of using memcpy

Recommended Posts

GekkoCube    116
whats the difference and when do i use these ?? memcpy( destination, source, strlen(source) ); memcpy( destination, source sizeof(source) ); ...im guessing the strlen(source) is for when source is a char*, and sizeof(source) is for when source is NOT a char*. ..?

Share this post


Link to post
Share on other sites
UltimaX    468
strlen returns the length of a string, not the size.
sizeof returns the size of the string.

sizeof will return the size of pretty much anything. Class, struct, char, int, etc.

-UltimaX-

"You wished for a white christmas... Now go shovel your wishes!"

Share this post


Link to post
Share on other sites
andy_fish    122
Yeah you should use strlen(source) if you are copying a string that''s referenced by a char*. If source is a char* and you were to call sizeof(source), you would only get the size of a pointer to a char, which is always 4 (I think).

A more obvious way of copying a string with memcpy would be:

memcpy( destination, source, sizeof(char) * strlen(source) );

as in, the size to copy is the number of characters times the size of a char. But the reason the person who wrote that code didn''t have the "sizeof(char)" part is because sizeof(char) is 1.

But an even better way to copy a string would be to use:

strcpy( destination, source );

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
don''t forget the NULL-terminator, without it it''s no longer a string:

memcpy( destination, source, sizeof(char) * (strlen(source)+1) );

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
however as memcpy copies bytes, we don''t need the sizeof operator when dealing with char arrays:
memcpy( destination, source, strlen(source)+1 );

Share this post


Link to post
Share on other sites