If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, string copy is the process of copying the content of one string to another. The strcpy()
function is used to copy one string to another.
The strcpy()
function is implemented in the <string.h>
library. It copies the content of the first string to the second string, including the null character. It returns a pointer to the destination string.
Here is an example of how to use the strcpy()
function:
Copy code
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[6];
strcpy(str2, str1);
printf("str2: %s", str2);
return 0;
}
In the above example, the content of str1
is copied to str2
. The output will be "str2: Hello".
It's important to note that strcpy()
function is not secure and should be avoided if you are working with strings that come from an untrusted source. This function can cause a buffer overflow if the destination buffer is not large enough to hold the entire source string, including the null character.
A safer alternative to strcpy()
is the strncpy()
function. It copies at most n
characters from the source string to the destination string, and it does not guarantee that the destination string is null-terminated.
Copy code
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[6];
strncpy(str2, str1, sizeof(str2));
str2[sizeof(str2) - 1] = '\0';
printf("str2: %s", str2);
return 0;
}
In this example, strncpy
only copies 5 characters from str1
to str2
(size of str2) and the last character of the str2 is set to '\0' so that it can be used as a proper string.
It's also worth noting that, strncpy()
is not very efficient in terms of performance, so it is recommended to use it only when you need to copy a fixed number of characters from a string.
Comments: 0