strcpy() function
Learn strcpy() function step by step with clear examples and exercises.
Why This Matters
In C programming, the strcpy() function plays a crucial role in handling and manipulating strings. A thorough understanding of this function can help you write cleaner, more efficient, and less error-prone code. This lesson will delve into the intricacies of the strcpy() function, including its usage, inner workings, common mistakes, practice questions, and frequently asked questions.
Prerequisites
Before diving into the strcpy() function, it is essential to have a solid grasp of the following concepts:
- C programming fundamentals, such as variables, data types, operators, control structures, and pointers
- Arrays in C
- Basic string manipulation functions like
strlen(),printf(), andscanf() - Pointers and their role in accessing and modifying arrays
Core Concept
Function Prototype and Syntax
The strcpy() function is declared in the string.h header file with the following prototype:
char *strcpy(char *destination, const char *source);
This function copies the string pointed to by the source pointer (including the null character) into the memory location pointed to by the destination pointer. The destination string is modified, and the function returns a pointer to the modified destination string.
How strcpy() Works
The strcpy() function copies each character from the source string to the corresponding index in the destination string until it encounters the null character (\0) in the source string or runs out of space in the destination array. It continues this process until the entire source string is copied into the destination array.
Worked Example
Here's an example demonstrating the usage of strcpy():
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "C programming";
char str2[20];
// Copying str1 to str2 using strcpy()
strcpy(str2, str1);
printf("Copied string: %s\n", str2); // Output: Copied string: C programming
return 0;
}
In this example, we have two character arrays str1 and str2. We copy the contents of str1 to str2 using the strcpy() function. After the copy operation, the modified str2 is printed to the console.
Internal Workings
The strcpy() function copies each character from the source string to the destination array by dereferencing both pointers and incrementing them until it encounters the null character in the source string or runs out of space in the destination array.
Example of strcpy()'s Internal Workings
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, World!";
char str2[10];
// Copying str1 to str2 using strcpy()
strcpy(str2, str1);
printf("Original strings:\n");
printf("str1: %s\n", str1); // Output: str1: Hello, World!
printf("str2: %s\n", str2); // Output: str2: Hello, World!
printf("\nModified strings:\n");
printf("str1: %s\n", str1); // Output: str1: Hello, World! (unchanged)
printf("str2: %s\n", str2); // Output: str2: Hello, World! (modified)
return 0;
}
In this example, we have two character arrays str1 and str2. We copy the contents of str1 to str2 using the strcpy() function. After the copy operation, both strings are printed to the console. You can see that the original string str1 remains unchanged, while the modified str2 contains the copied string.
Common Mistakes
- Buffer Overflow: If the destination buffer is not large enough to hold the source string, the program may result in undefined behavior or a segmentation fault. To avoid this, always ensure that the destination buffer has enough space to store the copied string, including the null character.
char str1[20] = "This is a long string"; // Buffer overflow!
char str2[30]; // Enough space for the copied string
strcpy(str2, str1);
- Forgetting the Destination Initialization: If you forget to initialize the destination array before copying a string using
strcpy(), the contents of the memory location pointed to by the destination pointer are undefined and may cause unexpected behavior.
char str1[20] = "Hello, World!";
char str2; // Not enough space for the copied string
strcpy(str2, str1); // Undefined behavior due to insufficient buffer size
- Using strcpy() with Non-String Pointers: The
strcpy()function expects its destination pointer to point to a character array (string). Using it with a non-string pointer may result in undefined behavior or a segmentation fault.
int arr[5] = {1, 2, 3, 4, 5};
char *str = "Hello, World!";
char *ptr = arr; // ptr points to an integer array, not a string
strcpy(ptr, str); // Undefined behavior due to using strcpy() with non-string pointer
Practice Questions
- Write a C program that copies the contents of two strings using
strcpy()and checks if they are equal or not. - Modify the example provided in the "Worked Example" section so that the destination buffer is not large enough to hold the source string, and observe the resulting behavior.
- Write a C program that uses
strcpy()to reverse a given string without using any additional arrays or functions. - Write a C program that copies a substring from one position to another within a string using
strcpy(). - Challenge: Implement a safe version of
strcpy()that checks the destination buffer size before copying and returns an error message if the buffer is too small.
FAQ
- Why does strcpy() return the destination pointer?: The
strcpy()function returns the modified destination pointer for convenience, allowing you to chain multiple string operations together in a single line of code. However, it's not necessary to use the returned value if you don't need to perform further operations on the same destination string.
- Is strcpy() thread-safe?: No,
strcpy()is not thread-safe because it does not provide any synchronization mechanisms for concurrent access to the shared string buffer. In a multi-threaded environment, use thread-safe alternatives likestrlcpy()from thestring.hheader file or custom implementations with synchronization primitives.
- What is the time complexity of strcpy()?: The time complexity of
strcpy()is O(n), where n is the length of the source string, because it needs to copy each character in the source string one by one into the destination array. This makes it less efficient for large strings compared to other string-copying functions with constant time complexity, such asmemmove().