C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
You always have to reserve enough character array space to hold the longest string you
will need to hold, plus the string terminator. You can define more array characters than
needed, but not fewer than you need.

If you want, you can store a string value in the array at the same time you define the array:


Click here to view code image


char month[10] = "January"; /* Defines a character array */

Figure 6.2 shows you what this array looks like. Because nothing was put in the last two places of the
array (January takes only seven characters plus an eighth place for the null zero), you don’t know
what’s in the last two places. (Some compilers, however, fill the unused elements with zeroes to kind
of empty the rest of the string.)


FIGURE 6.2 Defining and initializing an array named month that holds string data.

Each individual piece of an array is called an element. The month array has 10 elements. You can
distinguish between them with subscripts. Subscripts are numbers that you specify inside brackets
that refer to each of the array elements.


All array subscripts begin with 0. As Figure 6.2 shows, the first element in the month array is called
month[0]. The last is called month[9] because there are 10 elements altogether, and when you
begin at 0 , the last is 9.


Each element in a character array is a character. The combination of characters—the array or list of
characters—holds the entire string. If you wanted to, you could change the contents of the array from
January to March one element at a time, like this:


Click here to view code image


Month[0] = 'M';
Month[1] = 'a';
Month[2] = 'r';
Month[3] = 'c';
Month[4] = 'h';
Month[5] = '\0'; //You must add this

It is vital that you insert the null zero at the end of the string. If you don’t, the month array would still
have a null zero three places later at Month[7]; when you attempted to print the string, you would
get this:


Marchry
Free download pdf