Initialization of character arrays

You can initialize a one-dimensional character array by specifying:

Initializing a string constant places the null character (\0) at the end of the string if there is room or if the array dimensions are not specified.

The following definitions show character array initializations:

   static char name1[ ] = { 'J', 'a', 'n' };
   static char name2[ ] = { "Jan" };
   static char name3[4] = "Jan";

These definitions create the following elements:

Element Value Element Value Element Value
name1[0] J name2[0] J name3[0] J
name1[1] a name2[1] a name3[1] a
name1[2] n name2[2] n name3[2] n
    name2[3] \0 name3[3] \0

Note that the following definition would result in the null character being lost:

   static char name3[3]="Jan";

C++ When you initialize an array of characters with a string, the number of characters in the string — including the terminating '\0' — must not exceed the number of elements in the array.



[ Top of Page | Previous Page | Next Page | Contents | Index ]