Next: String Output Up: Arrays Previous: Arrays as parameters of

Strings in C++

So far the only form of character information used has been single characters which are defined as being of type char. Character strings have also been used in output.

A new data type is now considered, namely, the character string, which is used to represent a sequence of characters regarded as a single data item. In C++ strings of characters are held as an array of characters, one character held in each array element. In addition a special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Hence if a string has n characters then it requires an n+1 element array (at least) to store it. Thus the character `a' is stored in a single byte, whereas the single-character string "a" is stored in two consecutive bytes holding the character `a' and the null character.

A string variable s1 could be declared as follows:

char s1[10];

The string variable s1 could hold strings of length up to nine characters since space is needed for the final null character. Strings can be initialised at the time of declaration just as other variables are initialised. For example:

char s1[] = "example";
char s2[20] = "another example"
would store the two strings as follows:
s1  |e|x|a|m|p|l|e|\0|

s2  |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|

In the first case the array would be allocated space for eight characters, that is space for the seven characters of the string and the null character. In the second case the string is set by the declaration to be twenty characters long but only sixteen of these characters are set, i.e. the fifteen characters of the string and the null character. Note that the length of a string does not include the terminating null character.



Subsections

Next: String Output Up: Arrays Previous: Arrays as parameters of