- Strcpy
The C programming language offers a library function called strcpy, defined in the
string.h header file, that allows null-terminated memory blocks to be copied from one location to another. Since strings in C are not first-classdata type s and are implemented instead as contiguous blocks ofbyte s in memory, strcpy will effectively copy strings given twopointer s to blocks of allocated memory.The prototype of the function is: [ [http://www.cplusplus.com/reference/clibrary/cstring/strcpy.html strcpy - C++ Reference ] ] The return value is
destination
.Usage and implementation
For exampleIn the first two lines memory is allocated to hold two strings storing the memory addresses in str1 and str2. Next the memory pointed by str1 is filled using some user-input string. After that the string is copied from one memory block into the other. Although the simple assignment str2 = str1 might appear to do the same thing, it only copies the memory address of str1 into str2 but not the actual string. Both str1 and str2 would refer to the same memory block. This is known as a
shallow copy because it does not actually create a new, identical string.The strcpy function performs a copy by iterating over the individual characters of the string and copying them one by one. An explicit implementation of strcpy (there are more compact possibilities) is:
Wikimedia Foundation. 2010.