Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

8.8 Copying Strings

string.h

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.

Prototype
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:

  1. char student1[35] = "Jane Smith";
  2. char student2[35];

which results in the two arrays:

The function call

  1. 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.

Note
Note
It is important to note that the destination array must be large enough to store the entire resulting string including the null character. No range checking is performed to make sure there is enough room for the entire string and the null character.
Question 8.8.1

Consider the following code segment, which contains an error:

  1. char fruit[6] = "apple";
  2. 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.

Question 8.8.2

Suppose C did not provide the strcpy function. Implement your own version of the function that works identical to the original.