View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Strcpy in C: How to Copy Strings with Examples

Updated on 24/04/20253,947 Views

In C programming, strcpy in C is a standard library function used to copy one string into another. It simplifies string manipulation by allowing direct character transfer from a source string to a destination string. This function is widely used when handling character arrays, especially in applications that require low-level memory control.

Explore Online Software Engineering Courses from top universities.

In this article, we will explore what strcpy() does, how it works, and when to use it. You will learn its syntax, understand its return value, and see practical examples at various difficulty levels. We will also discuss its advantages, limitations, and important safety considerations.

What is Strcpy in C? 

In C programming, strcpy() is a standard library function used to copy the contents of one string (source) into another (destination). It is defined in the <string.h> header file. This function plays a key role in string manipulation, especially when working with character arrays.

The strcpy() function copies each character from the source string to the destination string until it encounters the null terminator ('\0'). Once copying is complete, the destination string becomes an exact copy of the source.

Let’s understand this with a simple example.

#include <stdio.h>
#include <string.h> // Required for strcpy()

int main() {
char source[] = "Hello, World!"; // Source string to copy
char destination[50]; // Destination string with enough space

strcpy(destination, source); // Copying source into destination

// Display the copied string
printf("Copied String: %s\n", destination);

return 0;
}

Output:

Copied String: Hello, World!

Explanation:

  • #include <string.h> – Includes the declaration of the strcpy() function.
  • char source[] = "Hello, World!"; – This is the string to be copied.
  • char destination[50]; – Declares a character array with enough space to hold the copied string.
  • strcpy(destination, source); – Copies all characters from source to destination, including the null character.
  • printf(...) – Prints the copied string to verify the result.

The strcpy() function is fast and efficient, but it does not check for buffer overflow. So, when using strcpy in C, make sure the destination array is large enough to hold the source string and the null terminator.

Syntax of Strcpy in C  

The strcpy() function in C is defined in the <string.h> header file. It copies the contents of one string into another. This function works at the predefined library level and uses two parameters: a destination and a source.

Here’s the syntax of strcpy() function in C:

char *strcpy(char *dest, const char *src);

Explanation of Components:

  • dest – This is the destination string where the content will be copied.
  • src – This is the source string which contains the original content.
  • Return Value – The function returns a pointer to the destination string (dest).

The destination should have enough memory allocated to store the entire source string, including the null terminator.

To help you better understand the syntax, here’s an example:

#include <stdio.h>
#include <string.h> // Required for strcpy()

int main() {
char src[] = "C programming"; // Source string
char dest[30]; // Destination with enough space

// Copy src to dest using strcpy()
char *result = strcpy(dest, src);

// Print the result
printf("Destination: %s\n", dest);
printf("Returned Pointer: %s\n", result);

return 0;
}

Output:

Destination: C programming

Returned Pointer: C programming

Explanation:

  • strcpy(dest, src); – Copies "C programming" from src to dest.
  • result stores the return value of strcpy(), which points to dest.
  • Both printed lines confirm the destination string and the return value are the same.

In C, using strcpy() is straightforward. Just remember that the destination buffer must be large enough. If not, it may lead to undefined behavior.

Must Explore: Static Function in C: Definition, Examples & Real-World Applications

Strcpy in C: Practical Examples

Let’s look at how strcpy() in C works through practical examples. These will help you understand its behavior at different levels of complexity.

Basic Level: Copying a Simple String

Here’s a basic level example:

#include <stdio.h>
#include <string.h> // Required for strcpy()

int main() {
char source[] = "Welcome to C";
char destination[20]; // Ensure enough space

strcpy(destination, source); // Copying source into destination

printf("Copied String: %s\n", destination);

return 0;
}

Output:

Copied String: Welcome to C

Explanation:

  • source[] contains the original string.
  • destination[] is large enough to hold the copied string.
  • strcpy(destination, source) copies all characters including the null character ('\0').
  • The printed output confirms the copy was successful.

Also read the strlen() Function in C article!

Intermediate Level: Using strcpy() Inside a Loop

Here’s an intermediate level example:

#include <stdio.h>
#include <string.h>

int main() {
char names[3][30] = {"Ram", "Shubham", "Harsh"};
char copy[30];

for (int i = 0; i < 3; i++) {
strcpy(copy, names[i]); // Copy each name one by one
printf("Name %d Copied: %s\n", i + 1, copy);
}

return 0;
}

Output:

Name 1 Copied: Ram

Name 2 Copied: Shubham

Name 3 Copied: Harsh

Explanation:

  • An array of strings is declared using a 2D char array.
  • The loop iterates through each name and copies it into copy[].
  • strcpy() handles each string copy operation.
  • This approach is useful in file handling, record systems, or dynamic string processing.

Must Explore: Enumeration (or enum) in C article!

Advanced Level: Copying User Input Safely

Here’s an advanced level example:

#include <stdio.h>
#include <string.h>

int main() {
char input[100];
char message[100];

printf("Enter a message: ");
fgets(input, sizeof(input), stdin); // Takes user input with spaces

// Remove newline character if present
input[strcspn(input, "\n")] = '\0';

strcpy(message, input); // Copying user input

printf("Message Stored: %s\n", message);

return 0;
}

Output:

Enter a message: Learn C programming!

Message Stored: Learn C programming!

Explanation:

  • fgets() is used to safely read user input with spaces.
  • strcspn() helps remove the newline character that fgets() appends.
  • strcpy() then copies the cleaned input into the message[] array.
  • This method is safer than using scanf() for string input.

These examples show how strcpy in C can be used in different real-life scenarios - from basic operations to input handling.

Also read the C Function Call Stack article!

Advantages of Strcpy() Function in C

The strcpy() function in C offers several benefits when it comes to handling strings. It’s one of the most commonly used functions in the C string handling library. Below are the key advantages of using strcpy() in C programming:

  • Simple to Use: strcpy() has a clear syntax. You just need to pass the destination and source strings.
  • Quick String Copy: It performs string copying faster compared to manual character-by-character transfer.
  • Part of Standard Library: It is available in <string.h>, so you don’t need to create a custom function.
  • Maintains Readability: Using strcpy() makes the code shorter and easier to read, especially in large projects.
  • Supports Null Terminator: It automatically adds the '\0' at the end of the copied string.
  • Returns Destination Pointer: This allows chaining or direct use of the result if needed.
  • Compatible with Static and Dynamic Arrays: You can use it for both fixed-size arrays and dynamically allocated memory blocks.
  • Commonly Used in Legacy Code: It’s widely supported across platforms and compilers, which makes it useful for maintaining older C programs.

Must Explore: Library Function in C article!

Limitations of Strcpy() Function in C

While strcpy() in C is useful, it also comes with serious limitations. If not used carefully, it can lead to program crashes, undefined behavior, or security risks. Below are the major drawbacks every C programmer must be aware of.

  • No Bounds Checking: strcpy() does not check if the destination array is large enough. This can lead to buffer overflows.
  • Unsafe for User Input: If the source string is longer than expected, it can overwrite memory and corrupt data.
  • Can Cause Segmentation Faults: Copying into a null or uninitialized pointer causes a crash at runtime.
  • Cannot Handle Overlapping Memory: It fails if the source and destination memory overlap, unlike memmove().
  • No Built-in Error Reporting: It does not return any error if copying fails due to size or memory issues.
  • Requires Manual Memory Management: Developers must ensure enough space in the destination. Otherwise, the program becomes unsafe. Below is an example to help you understand this better.

Example: Unsafe Use of strcpy() in C

#include <stdio.h>
#include <string.h>

int main() {
char source[] = "This string is too long!";
char destination[10]; // Not enough space

strcpy(destination, source); // Unsafe operation

printf("Copied String: %s\n", destination);

return 0;
}

Output:

Copied String: This string is too long!

Explanation:

  • The destination array has space for only 10 characters.
  • The source contains more than 20 characters including the null terminator.
  • strcpy() blindly copies all characters, which leads to buffer overflow.
  • This overflow can overwrite adjacent memory or cause a crash.

Safe Alternative (Recommended)

Use strncpy() or strcpy_s() if you want safer copying with size limits.

strncpy(destination, source, sizeof(destination) - 1);
destination[sizeof(destination) - 1] = '\0'; // Null-terminate manually

This ensures safety while copying strings in C.

Conclusion

The strcpy in C function is a simple yet powerful tool to copy strings from one variable to another. It belongs to the standard C string library and is widely used in real-world applications. However, it should be handled with care to avoid unsafe behavior.

Use strcpy() in C when you know the size of your arrays and the input is predictable. For safer alternatives, especially when handling user input, prefer strncpy() or strcpy_s(). Mastering string handling is essential in C, and strcpy() is the first step. Use it wisely to write cleaner, faster, and more reliable programs.

FAQs

1. What does strcpy() do in C?

The strcpy() function in C copies a string from a source to a destination. It replaces the contents of the destination string with those of the source, including the null terminator '\0'. It does not perform boundary checks.

2. Which header file is needed for strcpy()?

To use strcpy() in your C program, you must include the <string.h> header file. This file contains standard string handling functions, including strcpy(), strlen(), strcmp(), and many others used for manipulating C-style strings.

3. What happens if the destination array is too small?

If the destination array is smaller than the source string, strcpy() causes a buffer overflow. This can lead to memory corruption, unpredictable behavior, or even program crashes. Always make sure the destination has enough space.

4. Does strcpy() return anything?

Yes. The strcpy() function returns a pointer to the destination string. This is useful for chaining operations or assigning the copied string to another variable. However, the return value is not always needed in basic use cases.

5. Can we copy strings without using strcpy()?

Yes, you can copy strings manually using a loop. But strcpy() simplifies the task and reduces code size. However, manual copying gives you better control over bounds checking and avoids the risks that come with strcpy().

6. What is the difference between strcpy() and strncpy()?

For a better understanding, here’s the difference in a tabular format:

Feature

strcpy()

strncpy()

Null Terminator

Automatically added

May not be added if limit is reached

Buffer Safety

No size check

Allows specifying max characters to copy

Speed

Generally faster

Slightly slower due to extra checks

Ideal Use Case

Controlled, fixed-size strings

User input, dynamic or unknown input size

7. Can strcpy() copy an empty string?

Yes, strcpy() can copy an empty string. When the source string is "", only the null terminator '\0' is copied to the destination. It doesn’t result in an error as long as the destination is valid.

8. Is strcpy() suitable for copying user input?

No, it is not safe for copying direct user input. If the input exceeds the destination buffer size, it can crash the program. For such cases, prefer strncpy() or safer variants like strcpy_s() if supported.

9. Can we use strcpy() with dynamically allocated memory?

Yes, strcpy() works with dynamically allocated memory. Just ensure the destination pointer is valid and points to a memory block large enough to hold the entire source string, including the null character.

10. Does strcpy() work with overlapping memory areas?

No, strcpy() is not designed to handle overlapping memory regions. Using it in such cases results in undefined behavior. If overlap is possible, use memmove() instead, as it safely handles overlapping memory blocks.

11. How to avoid strcpy() related errors?

To avoid errors, always allocate enough memory for the destination. Use safer alternatives like strncpy() or strcpy_s() if available. Always validate input sizes, especially when copying user-controlled or variable-length strings.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.