C language strcpy () function: Copy string
Header files: #include <string.h>
To define a function:
Char *strcpy (char *dest, const char *SRC);
Function Description: strcpy () copies the parameter SRC string to the address that the parameter dest refers to.
Return value: Returns the string start address of the parameter dest.
Additional Note: If the parameter dest refers to the memory space is not large enough, may cause buffer overflow (buffer Overflow) error situation, in the writing program please pay special attention, or use strncpy () to replace.
Example
#include <string.h>
Main () {
char a[30] = "string (1)";
Char b[] = "string (2)";
printf ("Before strcpy ():%s\n", a);
printf ("After strcpy ():%s\n", strcpy (A, b));
}
Execution results:
Before strcpy (): string (1) after
strcpy (): String (2)
C language strncpy () function: Copy the first n characters of a string
Header files: #include <string.h>
strncpy () is used to copy the first n characters of a string, which is a prototype:
char * strncpy (char *dest, const char *SRC, size_t N);
The parameter description dest is the target string pointer, and SRC is the source string pointer.
strncpy () copies the first n characters of the string src to the string dest.
Unlike strcpy (), strncpy () does not append a closing tag ' "to the Dest, which raises a number of perverse questions, as described in the following example.
Note: The areas of memory that Src and dest refer to cannot overlap, and dest must have enough space to place n characters.
Return value returns the string dest.
The function example copies 4 sets of strings.
#include <stdio.h>
#include <string.h>
int main (void) {
char dest1[20];
Char src1[] = "abc";
int n1 = 3;
Char dest2[20]= "********************";
Char src2[] = "ABCXYZ";
int n2 = strlen (src2) +1;
Char dest3[100] = "http://see.xidian.edu.cn/cpp/shell/";
Char src3[6] = "ABCXYZ"; No ' n3 '
int =;
Char dest4[100] = "http://see.xidian.edu.cn/cpp/u/yuanma/";
Char src4[] = "Abc\0defghigk";
int N4 = strlen (SRC3);
strncpy (Dest1, SRC1, N1); N1 is less than strlen (STR1) +1, will not append ' the ' to '
strncpy (Dest2, Src2, N2);//N2 equals strlen (str2) +1, which can be copied to
Src2 at the end of Dest2 strncpy (Dest3, SRC3, N3); N3 is greater than strlen (STR3) +1, recycled copies str3
strncpy (Dest4, SRC4, N4);///SRC4 in the middle of the ""
("dest1=%s\n", dest1);
printf ("dest2=%s, dest2[15]=%c\n", Dest2, dest2[10]);
printf ("dest3=%s\n", dest3);
printf ("dest4=%s, dest4[6]=%d, dest4[20]=%d, dest4[90]=%d\n", Dest4, Dest4[6], dest4[20], dest4[90));
return 0;
}
VC6.0 Run Result:
MinGW Run Result:
From the above operation results can be seen, strncpy () difficult to control, behavior bizarre. The safest way to use strncpy () is to make n equal to strlen (SRC) +1, which is to copy the entire string and append ' to ' dest. But this has nothing to do with the role of strcmp ().