C Programming: strcpy vs. memcpy - A Detailed Comparison
Both 'strcpy' and 'memcpy' are functions in the C programming language used to copy data from one memory location to another.
'strcpy' is used to copy a string from one memory location to another. It takes two arguments: the destination string and the source string. The destination string must be large enough to hold the source string, or else the function may cause a buffer overflow. The function copies the source string to the destination string, including the terminating null character.
Example:
char source[] = "Hello, world!";
char destination[20];
strcpy(destination, source);
After executing the above code, the destination string will contain 'Hello, world!'.
'memcpy', on the other hand, is used to copy a block of memory from one location to another. It takes three arguments: the destination memory address, the source memory address, and the number of bytes to copy. The function does not check if the destination buffer is large enough to hold the source data, so it is up to the programmer to ensure that the destination buffer is of sufficient size.
Example:
int source[] = {1, 2, 3, 4, 5};
int destination[5];
memcpy(destination, source, sizeof(source));
After executing the above code, the destination array will contain {1, 2, 3, 4, 5}.
原文地址: https://www.cveoy.top/t/topic/ke3R 著作权归作者所有。请勿转载和采集!