GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C++ cstring strcpy() Function
Selected Reading
C++ cstring strcpy() FunctionThe C++ cstring strcpy() function is used to copy a string from one memory location to another memory location. It works by copying the string until it reaches the null character '\0'. It is important to keep in mind that the destination string must have enough space to store the source string. If the destination string is smaller than the source string, it will cause a buffer overflow. This function takes two arguments, the destination string and the source string. SyntaxThe syntax of the C++ cstring strcpy() function is − char *strcpy(char *destination, const char *source); ParametersFollowing are the parameters of the strcpy() function −
Return ValueThe strcpy() function returns a pointer to the destination, which is the same as the destination pointer passed as the first argument. Example 1In this example, we will try to copy the content of one string to another string using the strcpy() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char source[] = "Hello, World!";
char destination[100];
// Copying the content of source string to destination string
strcpy(destination, source);
cout << "Source: " << source << endl;
cout << "Destination: " << destination << endl;
return 0;
}
OutputWhen you run the program, the output will be − Source: Hello, World! Destination: Hello, World! Example 2In this example, we will us take less space in the destination string than the source string. We will then copy the content of the source string to the destination string using the strcpy() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char source[] = "Hello, World!";
char destination[4];
// Copying the content of source string to destination string
strcpy(destination, source);
cout << "Source: " << source << endl;
cout << "Destination: " << destination << endl;
return 0;
}
OutputWhen you run the program, the output will be: Source: , World! Destination: Hello, World! As you can see the output, it is not what we had expected. Output may vary depending on the compiler and the system you are using. It is always recommended to use the strncpy() function instead of strcpy() function to avoid buffer overflow. Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |