How to Copy String in C: Syntax and Examples
In C, you copy a string using the
strcpy function from string.h. It copies the content of one string into another, including the ending null character.Syntax
The strcpy function copies the source string into the destination string, including the null terminator.
- dest: A character array where the string will be copied.
- src: The source string to copy from.
c
char *strcpy(char *dest, const char *src);Example
This example shows how to copy one string into another using strcpy and then print the copied string.
c
#include <stdio.h> #include <string.h> int main() { char source[] = "Hello, friend!"; char destination[50]; strcpy(destination, source); printf("Copied string: %s\n", destination); return 0; }
Output
Copied string: Hello, friend!
Common Pitfalls
Common mistakes when copying strings in C include:
- Not allocating enough space in the destination array, which can cause buffer overflow.
- Forgetting to include
string.hto usestrcpy. - Using
strcpywith overlapping source and destination strings, which is unsafe.
Always ensure the destination array is large enough to hold the source string plus the null terminator.
c
#include <stdio.h> #include <string.h> int main() { char source[] = "Hello, friend!"; char destination[5]; // Too small! // Unsafe: may cause buffer overflow // strcpy(destination, source); // Safe way: use strncpy to limit copy size strncpy(destination, source, sizeof(destination) - 1); destination[sizeof(destination) - 1] = '\0'; // Ensure null termination printf("Copied string safely: %s\n", destination); return 0; }
Output
Copied string safely: Hell
Quick Reference
| Function | Description | Notes |
|---|---|---|
| strcpy(dest, src) | Copies entire src string to dest | Dest must be large enough |
| strncpy(dest, src, n) | Copies up to n characters | May not null-terminate if src longer than n |
| memcpy(dest, src, n) | Copies n bytes (not string safe) | Use only if you know exact size |
Key Takeaways
Use
strcpy to copy strings safely when destination has enough space.Always include
string.h to use string functions like strcpy.Avoid buffer overflow by ensuring destination array size is sufficient.
Use
strncpy if you want to limit the number of characters copied.Never use
strcpy with overlapping source and destination strings.