Programming in C

(Barry) #1
Variable-Length Character Strings 199

fashion, you can eliminate the need to specify the number of characters that are con-
tained inside a character string.
In the C language, the special character that is used to signal the end of a string is
known as the nullcharacter and is written as '\0'.So, the statement


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


defines a character array called wordthat contains sevencharacters, the last of which is
the null character. (Recall that the backslash character [] is a special character in the C
language and does not count as a separate character; therefore,'\0'represents a single
character in C.) The array wordis depicted in Figure 10.2.


'H'

'l'
'l'

'!'

word[1]
word[2]
word[3]

'e'

'o'

word[0]

word[5]

word[4]

word[6] '\0'

Figure 10.2 The array wordwith a terminating null character.

To begin with an illustration of how these variable-lengthcharacter strings are used, write
a function that counts the number of characters in a character string, as shown in
Program 10.2. Call the function stringLengthand have it take as its argument a charac-
ter array that is terminated by the null character.The function determines the number of
characters in the array and returns this value back to the calling routine. Define the
number of characters in the array as the number of characters up to, but not including,
the terminating null character. So, the function call


stringLength (characterString)


should return the value 3 if characterStringis defined as follows:


char characterString[] = { 'c', 'a', 't', '\0' };


Program 10.2 Counting the Characters in a String


// Function to count the number of characters in a string


#include <stdio.h>

Free download pdf