8.8 Copying Strings
Since strings are implemented as character arrays, you can not copy a string with a simple assignment as you can do in Python. To copy a string in C, the characters that comprise the C-style string in an array must be copied, character by character to a second array. This can be done using the strcpy function.
|
The String Copy Function
string.h
char[] strcpy(char dest[], char src[]);
The function takes a character array
src that contains a string and copies it to a second character array, dest. The destination must be large enough to store the entire string, including the null character. |
Consider the array declarations:
- char student1[35] = "Jane Smith";
- char student2[35];
which results in the two arrays:
The function call
- strcpy(student2, student1);
will copy the source string character by character from the student1 array to the destination student2 array. The null character is appended to the end of the new string.

Consider the following code segment, which contains an error:
- char fruit[6] = "apple";
- strcpy(fruit, "applesauce");
Identify the error.
The character array fruit was defined with 6 elements, which is sufficient for storing the string "apple". When we copy the longer string "applesauce" to the array, it overflows the array, which will result in a logic or run-time error.

