Two methods are available for initializing character arrays. One is to use character constants for initialization, and the other is to use string constants for initialization.
1. initialize with a character constant
The syntax format for initializing with character constants is:
<Array name> [<constant expression 1>] [<constant expression 2>]… [<Constant expression n>] ={{ <character constant initial value table 1 >}, {<character constant initial value table 2> },..., {<Character constant initial value table n> }};
For example:
Char S1 [8] = {'C', 'O', 'M', 'P', 'U', 't', 'E', 'R '}, s2 [10] = {'M', 'O', 'U', 's', 'E '};
Char S3 [2] [5] = {'B', 'O', 'O', 'K'}, {'B', 'O', 'O ', 'k', '2 '}};
2. initialize with a String constant
In C ++, character constants, character variables, and string constants are available, but no variables are set to store strings. Character Arrays can be used to process strings. Therefore, you can use string constants to initialize character arrays.
The syntax format for initializing character arrays with string constants is:
<Array name> [<constant expression 1>] [<constant expression 2>]… [<Constant expression n>] ={{ <"String constant 1" >}, {<"String constant 2"> },..., {<"String constant N"> }};
For example:
{Char S11 [9] = {"computer"}, s22 [10] = "Mouse ";
Char s33 [2] [5] = {"box", "boxs "};//
Table 6-3 lists the data values of each element after the six arrays are initialized.
Note:
(1) If the number of characters is greater than the length of the array, a syntax error is prompted;
(2 When initializing character arrays with strings, the system will automatically add a character '\ 0' at the end of the character array '. Therefore, consider that the length of the array is 1 larger than the actual number of characters.;
(3) When initializing a one-dimensional character array with a string, braces can be omitted {}.