some scenarios of using memcpy

Started by
3 comments, last by GekkoCube 20 years, 8 months ago
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*. ..?
Advertisement
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!"
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 );
don''t forget the NULL-terminator, without it it''s no longer a string:

memcpy( destination, source, sizeof(char) * (strlen(source)+1) );
however as memcpy copies bytes, we don''t need the sizeof operator when dealing with char arrays:
memcpy( destination, source, strlen(source)+1 );

This topic is closed to new replies.

Advertisement