Comparison between strcpy () and memcpy ()

Source: Internet
Author: User

Most of these two functions usually use strcpy () but ignore memcpy (). They all copy content from the buffer zone.

Byte A [4]; // Value Type assigned to each byte
A [0] = 0;
A [1] = 1;
A [2] = 0;
A [3] = 1;

Byte c1 [4];
Memcpy (C1, A, sizeof (byte) * 4 );
Byte c2 [4];
Strcpy (char *) (byte *) C2, (char *) (byte *) );

Only memcpy () is correct, so compare them with their function prototype:

Char * strcpy (char * strdest, const char * strsource );

Void * memcpy (void * DEST, const void * SRC, size_t count );

We can see that strncpy () is the string to be processed (in case of zero termination), memcpy () is to process a buffer (void * type), and our content contains numbers 0, the number 0 represents the number of the string ending character '\ 0'. The string copy operation ends when it reaches 0. Therefore, if the buffer to be copied is non-string, use memcpy () as far as possible to avoid errors.
-------------------------------------------------------------------------
Void * memcpy (void * pvto, const void * pvfrom, size_t size)
{
Assert (pvto! = NULL) & (pvfrom! = NULL); // Use assertions
Byte * pbto = (byte *) pvto; // prevents the pvto address from being changed
Byte * pbfrom = (byte *) pvfrom; // prevents the pvfrom address from being changed
 
While (size --> 0)
* Pbto ++ = * pbfrom ++;
 
Return pvto;

}

Char * strcpy (char * strdest, const char * strsrc)
{
Assert (strdest! = NULL) & (strsrc! = NULL ));
 
Char * address = strdest;
While (* strdest ++ = * strsrc ++ )! = '')
Continue;

Return address;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.