I encountered a character array problem during my fcitx input method during my internship last week. Due to the poor foundation, I found the problem after debugging for several minutes.
There are two common character array initialization formats:
Char Arr_test [ 10 ] = { ' H ' , ' E ' , ' L ' , ' L ' , ' O ' , ' W ' , ' O ' , ' R ' , ' L ' ,' D ' };
And
CharArr_test [11] ="Helloworld";
Why is the same content? The two arrays have different lengths. One is 10 and the other is 11, because the string Terminator '\ 0' is added to the second array by default '. In this case, we need to use strlen (arr_test) to calculate the length of the two arrays. what is the answer?
The first array is obtained using strlen (arr_test). The length is not fixed. Why? Because strlen does not encounter '\ 0', it does not know when it will end.
The second array is obtained using strlen (arr_test). The length is 10. Why? Take a look at my previousArticleDifferences between sizeof in C/C ++ and strlen.
TestProgram:
Test procedure 1:
# Include <iostream> Using Namespace STD; Int Main (){ Char Arr_test [ 10 ] = { ' H ' , ' E ' , ' L ' ,' L ' , ' O ' , ' W ' , ' O ' , ' R ' , ' L ' , ' D ' }; Cout < " Strlen (arr_test) = " <Strlen (arr_test) < Endl; cout < " Sizeof (arr_test) = " < Sizeof (Arr_test) <Endl; Return 0 ;}
Output result:
Strlen (arr_test) = 15
Sizeof (arr_test) = 10
Test Procedure 2:
# Include <iostream> Using Namespace STD; Int Main (){ Char Arr_test [ 10 ] = " Helloworld " ; Cout < " Strlen (arr_test) = " <Strlen (arr_test) < Endl; cout < " Sizeof (arr_test) = " < Sizeof (Arr_test) < Endl; Return 0 ;}
Output result:
The compilation fails. Error c2117: 'helloworld': Array Bounds Overflow
Test 3:
# Include <iostream> Using Namespace STD; Int Main (){ Char Arr_test [ 11 ] = " Helloworld " ; Cout < " Strlen (arr_test) = " <Strlen (arr_test) < Endl; cout < " Sizeof (arr_test) = " < Sizeof (Arr_test) < Endl; Return 0 ;}
Output result:
Strlen (arr_test) = 10
Sizeof (arr_test) = 11
Test 4:
# Include <iostream> Using Namespace STD; Int Main (){ Char Arr_test [ 11 ] = { ' H ' , ' E ' , ' L ' , ' L ' , ' O ' , ' W ' , ' O ' , ' R ' , ' L ' , ' D ' , ' \ 0 ' }; Cout < " Strlen (arr_test) = " <Strlen (arr_test) < Endl; cout < " Sizeof (arr_test) = " <Sizeof (Arr_test) < Endl; Return 0 ;}
Output result:
Strlen (arr_test) = 10
Sizeof (arr_test) = 11
Here we will mention sizeof and strlen:
Sizeof isBytesNote that int occupies 4 bytes in 32-bit hosts.
Strlen only works as a counter. It starts scanning from a memory location (which can start with a string, a location in the middle, or even an uncertain memory area, the counter value is returned until the first string Terminator '\ 0' is reached.