The differences between C and memcpy are described in detail

  • 2020-05-12 02:54:21
  • OfStack

The differences between strcpy and memcpy in C languages are described in detail

PS: beginner algorithm, start brush leetcode, Rotate array preparatory knowledge (write the code Time Limit Exceed sad) so baidu efficient algorithm, this article as preparatory knowledge.

1. strcpy and strncpy functions

This is a familiar one. I learned C in college, and it's called strcpy (character array 1, string 2) and it copies string 2 into character array 1.
EX:


char str1[10]='',str2[]={"China"}; 
strcpy(str1,str2); 

strncpy (str1 str2, 2); The function is to copy the first two characters in str2 into str1, replacing the first two characters in str1.

2. memcpy function

The memory copy function used by c and c++. The function memcpy copies n bytes from the starting location of the memory address referred to by the source src to the starting location of the memory address referred to by the target dest.
Usage: void *memcpy(void *dest, const void *src, size_t n);

EX:


char *s1 = "csdn"; 
char *s2 = new char[10]; 
char *s3 = memcpy(s2,s1,5); 

3. Difference between strcpy and memcpy.

1. Different contents are copied. While strcpy can only copy strings, memcpy can copy anything, such as character arrays, integers, structs, classes, and so on.
2. Different methods of replication. strcpy does not need to specify a length; it only ends when it encounters the string terminator "\0" of the copied character, so it is prone to overflow. memcpy determines the length of replication according to its third parameter.
3. Different USES. strcpy is usually used for copying strings, and memcpy is usually used for copying other types of data

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: