The difference between sprintf, strcpy and memcpy

Source: Internet
Author: User



To do a problem with the sprintf to write a character array (string) into a two-dimensional character array, and then take a long time, think of strcpy seems to be able to, it turns out that strcpy efficiency is even higher, and then think of the memcpy seems to be able to think. Practice a bit really can, efficiency needless to say also higher than sprintf, after all, memcpy is the memory operation. Then I will Baidu a bit of their differences, make a summary (note).


  • sprintf can use%s to implement formatted writes, and the other two cannot.
  • The strcpy encounters the end of the (also copied) and can only copy strings.
  • memcpy is copied according to size, and can replicate various data types (struct, array).


For the copy string, we select strcpy, because memcpy also needs to supply the size parameter, and strcpy another advantage is that the return value is char *, which is the first address of the target string, so that the chained expression can be written:



Strlen (strcpy (s1,strcpy (DEST,SRC)));


The realization of strcpy
char * strcpy (char * strDest, const char * strSrc); // copy strSrc to strDest

{
If ((strSrc == NULL) || (strDest == NULL)) // Judging parameter validity
{
Return NULL;
}
Char * dest = strDest; // Save the first address of the target string
While ((* strDest ++ = * strSrc ++)! = ‘\ 0’); // Copy the contents of the src string to dest
Return dest;
}
The realization of memcpy
void * memcpy (void * memTo, const void * memFrom, size_t size)
{
If ((memTo == NULL) || (memFrom == NULL)) // memTo and memFrom must be valid
          return NULL;
Char * tempFrom = (char *) memFrom; // Save the first address of memFrom
Char * tempTo = (char *) memTo; // Save memTo first address
While (size-> 0) // loop size times, copy the value of memFrom to memTo
        * TempTo ++ = * tempFrom ++;
Return memTo;
} 


Related: string.h character functions commonly used in C language



The difference between sprintf, strcpy and memcpy


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.