Programming in C

(Barry) #1
Variable-Length Character Strings 201

Initializing and Displaying Character Strings


Now, it is time to go back to the concatfunction developed in Program 10.1 and
rewrite it to work with variable-length character strings. Obviously, the function must be
changed somewhat because you no longer want to pass as arguments the number of
characters in the two arrays.The function now takes only three arguments: the two char-
acter arrays to be concatenated and the character array in which to place the result.
Before delving into this program, you should first learn about two nice features that
C provides for dealing with character strings.
The first feature involves the initialization of character arrays. C permits a character
array to be initialized by simply specifying a constant character string rather than a list of
individual characters. So, for example, the statement


char word[] = { "Hello!" };


can be used to set up an array of characters called wordwith the initial characters ‘H’, ‘e’,
‘l’, ‘l’, ‘o’, ‘!’, and ‘\0’, respectively.You can also omit the braces when initializing character
arrays in this manner. So, the statement


char word[] = "Hello!";


is perfectly valid. Either statement is equivalent to the statement


char word[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' };


If you’re explicitly specifying the size of the array, make certain you leave enough space
for the terminating null character. So, in


char word[7] = { "Hello!" };


the compiler has enough room in the array to place the terminating null character.
However, in


char word[6] = { "Hello!" };


the compiler can’t fit a terminating null character at the end of the array, and so it
doesn’t put one there (and it doesn’t complain about it either).
In general, wherever they appear in your program, character-string constants in the C
language are automatically terminated by the null character.This fact helps functions
such as printfdetermine when the end of a character string has been reached. So, in
the call


printf ("Programming in C is fun.\n");


the null character is automatically placed after the newline character in the character
string, thereby enabling the printffunction to determine when it has reached the end
of the format string.
The other feature to be mentioned here involves the display of character strings.The
special format characters %sinside a printfformat string can be used to display an array
of characters that is terminated by the null character. So, if wordis a null-terminated
array of characters, the printfcall


printf ("%s\n", word);

Free download pdf