Interview point: String strcpy Function
Analysis of C language interview questions 2
I. Basic knowledge points
Strcpy (character array 1, string 2)
1. strcpy this function uses the string terminator of the second parameter to determine whether the copy ends;
2. The strlen function obtains the string length,It does not contain the string Terminator.;
3. When using the strcpy function, be sure to note that the size of the first character array is at least less than the size of string 2; otherwise, access is out of bounds;
4. The '\ 0' after string 2 is also copied to character array 1;
2. program error analysis part 1:
Void test1 ()
{
Char string [10];
Char * str1 = "0123456789 ";
Strcpy (string, str1 );
}
Here, the string array is out of bounds because the str1 character length is 10 and there is an Terminator '/0 '. So there are a total of 11 characters in length. The size of the string array is 10, so it is out of bounds.
PS: when using the strcpy function, you must note that the size of the preceding destination array must be greater than the size of the subsequent string. Otherwise, access is out of bounds.
Program Segment 2:
Void Test2 ()
{
Char string [10], str1 [10];
Int I;
For (I = 0; I <10; I ++)
{
Str1 [I] = 'a ';
}
Strcpy (string, str1 );
}
The biggest problem here is that str1 has no Terminator, because the second parameter of strcpy should be a String constant. This function is used to determine whether the copy ends by judging the terminator of the second parameter. Therefore, str1p [9] should be added after the for loop.
= '/0 ';
PS: The most obvious difference between character arrays and strings is that strings are appended with the terminator '/0' by default '.
Program fragment 3
Void test3 (char * str1)
{
Char string [10];
If (strlen (str1) <= 10)
{
Strcpy (string, str1 );
}
}
The problem here is still a cross-border problem. The strlen function obtains the length of the string except the Terminator. If the length of the STR string is equal to 10, it is obviously out of bounds.