How to Use strcpy in C: Syntax, Example, and Tips
In C, use
strcpy(destination, source) to copy a string from source to destination. Ensure destination has enough space to hold the copied string including the null character.Syntax
The strcpy function copies the string from the source to the destination buffer, including the terminating null character \0.
destination: A character array where the string will be copied.source: The string to copy.
Make sure destination has enough space to hold the copied string to avoid memory errors.
c
char *strcpy(char *destination, const char *source);Example
This example shows how to copy a string using strcpy and then print the copied string.
c
#include <stdio.h> #include <string.h> int main() { char source[] = "Hello, world!"; char destination[50]; // Make sure this is large enough strcpy(destination, source); printf("Copied string: %s\n", destination); return 0; }
Output
Copied string: Hello, world!
Common Pitfalls
Common mistakes when using strcpy include:
- Not allocating enough space in
destination, which can cause buffer overflow and crash the program. - Using
strcpywith overlapping source and destination buffers, which leads to undefined behavior. - Forgetting that
strcpycopies the null terminator, sodestinationmust be large enough for the entire string plus\0.
To avoid these issues, always ensure the destination buffer is large enough and consider using safer alternatives like strncpy if available.
c
#include <stdio.h> #include <string.h> int main() { char source[] = "Hello"; char destination[5]; // Too small, no space for '\0' // Wrong: may cause buffer overflow // strcpy(destination, source); // Right: allocate enough space char safe_destination[6]; strcpy(safe_destination, source); printf("Safe copy: %s\n", safe_destination); return 0; }
Output
Safe copy: Hello
Quick Reference
Remember these tips when using strcpy:
- Always allocate enough space in
destination. strcpycopies until it finds the null character\0.- Do not use
strcpyif source and destination overlap. - Consider safer alternatives like
strncpyfor bounded copying.
Key Takeaways
Use strcpy(destination, source) to copy strings in C, ensuring destination has enough space.
strcpy copies the entire string including the null terminator '\0'.
Avoid buffer overflow by allocating sufficient space for destination.
Do not use strcpy with overlapping source and destination buffers.
Consider safer alternatives like strncpy for bounded copying.