Programming in C

(Barry) #1

196 Chapter 10 Character Strings


Arrays of Characters


If you want to be able to deal with variables that can hold more than a single character,^1
this is precisely where the array of characters comes into play.
In Program 7.6, you defined an array of characters called wordas follows:
char word [] = { 'H', 'e', 'l', 'l', 'o', '!' };
Remembering that in the absence of a particular array size, the C compiler automatically
computes the number of elements in the array based upon the number of initializers, this
statement reserves space in memory for exactly six characters, as shown in Figure 10.1.


  1. Recall that the type wchar_tcan be used for representing so-called wide characters, but that’s
    for handling a single character from an international character set. The discussion here is about
    storing sequences of multiple characters.


'H'

'l'
'l'

'!'

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

'e'

'o'

word[0]

word[5]

word[4]

Figure 10.1 The arraywordin memory.

To print out the contents of the array word,you ran through each element in the array
and displayed it using the %cformat characters.
With this technique, you can begin to build an assortment of useful functions for
dealing with character strings. Some of the more commonly performed operations on
character strings include combining two character strings together (concatenation),
copying one character string to another, extracting a portion of a character string (sub-
string), and determining if two character strings are equal (that is, if they contain the
same characters). Take the first mentioned operation, concatenation, and develop a func-
tion to perform this task.You can define a call to your concatfunction as follows:
concat (result, str1, n1, str2, n2);
where str1and str2represent the two character arrays that are to be concatenated and
n1and n2represent the number of characters in the respective arrays.This makes the
function flexible enough so that you can concatenate two character arrays of arbitrary
length.The argument resultrepresents the character array that is to be the destination
of the concatenated character arrays str1followed by str2. See Program 10.1.
Free download pdf