Copying strings with strcpy
What you'll learn: How to safely duplicate the contents of one string into another using the strcpy function.
The "Bucket" Problem
In C, strings aren't like regular numbers. You can't just use the equals sign (=) to copy one to another. If you have char str1[] = "Hello"; and char str2[10];, writing str2 = str1; will cause a compiler error.
Think of a string as a row of lockers. You can’t move the entire row just by pointing at it; you have to physically take the items out of each locker in the first row and place them into the lockers in the second row. The strcpy function (short for "string copy") is the automated assistant that does this heavy lifting for you.
Using strcpy
To use this tool, you must include the <string.h> header at the top of your code. The function takes two arguments: the destination (where the text is going) and the source (where the text is coming from).
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "C Programming";
char destination[20]; // Make sure this is big enough!
// Syntax: strcpy(destination, source);
strcpy(destination, source);
printf("Source: %s\n", source);
printf("Copied: %s\n", destination);
return 0;
}
When strcpy runs, it starts at the first character of the source and copies it to the destination. It keeps going until it hits the null terminator (\0), which tells it the string has ended. It copies that null terminator too, ensuring the new string is properly finished.
The Golden Rule: Size Matters
The most important thing to remember is that the destination must be large enough to hold the incoming text. If you try to copy a 20-character sentence into a 5-character array, strcpy won't stop at the edge. It will spill over into memory it doesn't own, which usually leads to your program crashing or behaving unpredictably. Always ensure your destination array has enough "lockers" to fit every character plus the invisible null terminator.
Key takeaway
Use strcpy(dest, src) to copy text from one array to another, but always ensure the destination array is large enough to hold the source string.