Character Constants as Initializers

The declaration char color[] = "blue"; could also be written

char color[] = { 'b', 'l', 'u', 'e', '' };

which uses character constants in single quotes (') as initializers for each element of the built-in array. When declaring a built-in array of chars to contain a string, the built-in array must be large enough to store the string and its terminating null character. The compiler determines the size of the built-in array in the preceding declaration, based on the number of initializers in the initializer list.


Image Common Programming Error 8.7

Not allocating sufficient space in a built-in array of chars to store the null character that terminates a string is a logic error.



Image Common Programming Error 8.8

Creating or using a C string that does not contain a terminating null character can lead to logic errors.



Image Error-Prevention Tip 8.7

When storing a string of characters in a built-in array of chars, be sure that the built-in array is large enough to hold the largest string that will be stored. C++ allows strings of any length. If a string is longer than the built-in array of chars in which it’s to be stored, characters beyond the end of the built-in array will overwrite data in memory following the built-in array, leading to logic errors and potential security breaches.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.251