Jump to content
  • Advertisement

Archived

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

GekkoCube

some scenarios of using memcpy

This topic is 5427 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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!"

Share this post


Link to post
Share on other sites
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
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
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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!