In C++, copying a string involves creating a new string that has the same contents as the original string.
There are different ways to copy strings in C++, but in this tutorial, we will focus on the traditional way of copying strings using the standard library function strcpy().
The strcpy() function is defined in the header file and takes two arguments: the destination string and the source string.
It copies the contents of the source string to the destination string until it reaches a null character (‘\0’).
Here is an example program that demonstrates how to use strcpy() to copy a string:
#include <iostream>
#include <cstring>
int main() {
char source[] = "Hello, world!";
char destination[20];
std::strcpy(destination, source);
std::cout << "Source string: " << source << std::endl;
std::cout << "Destination string: " << destination << std::endl;
return 0;
}
In this example, we first declare the source string source and the destination string destination.
We then use strcpy() to copy the contents of source to destination. Finally, we print both strings to the console to confirm that the copy was successful.
One thing to note is that strcpy() does not check for buffer overflow, which means that it can potentially overwrite memory beyond the bounds of the destination string.
To avoid this, we can use the safer strncpy() function, which takes an additional argument specifying the maximum number of characters to copy.
Here is an example program that uses strncpy() to copy a string:
#include <iostream>
#include <cstring>
int main() {
char source[] = "Hello, world!";
char destination[20];
std::strncpy(destination, source, sizeof(destination));
std::cout << "Source string: " << source << std::endl;
std::cout << "Destination string: " << destination << std::endl;
return 0;
}
In this example, we use strncpy() instead of strcpy() and specify the size of the destination buffer as the maximum number of characters to copy.
This ensures that we don’t copy more characters than the destination buffer can hold.
In conclusion, copying strings is a common operation in C++, and the standard library provides several functions to make it easy.
By using strcpy() or strncpy(), we can copy the contents of one string to another and ensure that our program doesn’t crash due to buffer overflow.




