The difference between these functions is that the implementation functions and the operation objects are different.
The strcpy function operates on a string to copy the source string to the target string.
Objects operated by the snprintf function are not limited to strings: although the target object is a string, the source object can be a string or any basic type of data. This function is mainly used to convert (string or basic data type) to a string. If the source object is a string and the % s format character is specified, you can also copy the string.
The memcpy function, as its name implies, is a memory copy function that copies the content of one memory block to another. The memory block is determined by its first address and length. The entity object that appears in the program, no matter what type, is expressed as occupying a place (a memory interval or block) in the memory ). Therefore, memcpy's operation object is not limited to a certain type of data, or can be applied to any data type, as long as it can provide the initial address and Memory Length of the object, and the object can be operable. In view
Memcpy functions and other features of long copies and the physical meaning of data types. memcpy functions are generally limited to copying data of the same type or between objects, of course, it also includes copying strings and basic data types.
For string copying, the above three functions can be used, but their implementation efficiency and ease of use are different:
- Strcpy is undoubtedly the most appropriate choice: High Efficiency and convenient calls.
- Snprintf requires additional format characters and format conversion, which is troublesome and inefficient.
- Although memcpy is efficient, it requires an additional parameter of the copied memory length, which is easy to error and inconvenient to use. If the length is too large (the optimal length is the length of the source string + 1 ), it will also bring about a reduction in performance. In fact, the strcpy function is generally implemented internally by calling the memcpy function or using the Assembly directly to achieve efficient purposes. Therefore, using memcpy and strcpy to copy strings should have no major performance difference.
For non-string data replication, strcpy and snprintf are generally powerless, but there is no impact on memcpy. However, for basic data types, although memcpy can be used for copying, since the value assignment operator can be used to conveniently and efficiently copy data of the same or compatible type, therefore, memcpy is rarely used in this case. Memcpy is used to copy the structure or array (usually internal). Its purpose is to be efficient, convenient to use, or even both.