Using Character Arrays

All of the examples in this chapter have used numeric arrays, but arrays can also store characters (which, yes, are technically integers). By creating an array of characters, you can create a string. This concept was introduced back in Chapter 2 but merits a review.

There are two important differences between character arrays and other array types. First, storing a string in a character array always requires an extra element. This extra, final element stores the terminating NULL character (), which marks the end of a string. Table 6.2 lists the elements for a character array called name with a value of Aubrey.

Table 6.2. A string stored in a character array is actually multiple individual characters terminated by the NULL character.
The name Array 
IndexValue
0A
1u
2b
3r
4e
5y
6

The second difference is that character arrays must be assigned a value using double quotation marks:

name[7] = "Aubrey";

Whereas number values do not use quotation marks and single-character values use single quotation marks, strings use double quotation marks. Notice that this syntax implies the NULL character, which does not need to be explicitly stated within double quotation marks.

Of course, you could assign strings to character arrays in a more tedious way, like this:

char name[7] = {'A', 'u', 'b', 'r', 'e',
 'y', ''};

But the double quotation technique is a handy feature to use.

This next example will take a user-submitted word and print it backwards by using the array indexes.

To use character arrays

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 6.6):

/* backwards.c - Script 6.6 */
#include <stdio.h>

Script 6.6. This simple application reads in a word from the standard input and then prints it in reverse order.


3.
Include the ctype.h library file:

#include <ctype.h>

This standard header file defines several functions that can be useful in validating single characters. In this particular example, the isalpha() function will be required. When we include ctype.h, that function becomes available to this application.

4.
Begin defining the main function:

int main (void) {

5.
Declare the required variables:

char input[11];
int i;
char junk;

The first variable, input, will be the character array used to store the keyed characters. The second variable, i, is the index variable, which will be used to help loop through the character array. Finally, junk is a single character used to help discard extraneous input.

6.
Prompt the user and read in the keyboard input:

printf ("Enter a word up to ten
 characters long: ");
scanf ("%10s", input);

The prompt itself is quite simple and self-explanatory. After it, the scanf() function is used to read up to a 10-character string (%10s). This will be assigned to the input variable (along with the eleventh character, which is the ). Because input is a string, you can refer directly to the variable rather than its address (&input). This concept and all of the important syntax was discussed in Chapter 5.

7.
Reprint the entered word:

printf ("The word '%s' is '", input);

The end result of the application (Figure 6.9) will be a prompt, followed by a line of text where the inputted word is printed both forwards and backwards. This print statement creates all of the text up until the word is printed backwards.

Figure 6.9. A short word is printed backwards by the application.


8.
Define the for loop:

for (i = 10; i >= 0; i--) {

Unlike the previous loop, this one will iterate through an array in reverse order. Instead of going from 0 to 10 in increments of 1, it counts down from 10 to 0 in decrements of 1. The consequence of this reverse structure is that the input array will be accessed in the opposite order it was entered.

9.
Print every character:

if (isalpha(input[i])) {
  printf ("%c", input[i]);
}

If the user enters a string only 5 characters long, there will be 5 unused spaces in the input array. Rather than include these in the backwards printout, the isalpha() function is used to verify that the element value is an alphabetical character. If the current array value passes this test, that character is printed.

Notice that the syntax for accessing array elements—input[i]—is the same even though the loop is working backwards through the array. In other words, you don't have to always loop through arrays in ascending order from 0.

10.
Complete the for loop and finish the feedback statement:

}
printf ("' spelled backwards.
");

This printf() statement completes the one begun in Step 7, including the closing single quotation mark that helps surround the backwards version of the word (Figure 6.9).

11.
Read in and discard any extraneous input:

do {
    junk = getchar();
} while (junk != '
'),

Since this application makes use of user input, it's a good idea to remove all extraneous input (for instance, if the user enters a word longer than 10 characters) using this trick.

12.
Complete the main function:

   getchar();
   return 0;
}

13.
Save the file as backwards.c, compile, and debug as necessary.

14.
Run the application, entering different values at the prompt (Figures 6.10 and 6.11).

Figure 6.10. Only 10 letters of a long word are read in and printed in reverse.


Figure 6.11. Improper input is more or less ignored by the application.


✓ Tips

  • It's possible that this example would print some garbage if a shorter word was entered. For example, if all eleven blocks of memory aren't used by the submitted word, whatever was present in those unused memory blocks would still be part of the input array. To correct for this, you could initialize the entire array by setting each value to NULL before assigning the user's input to it.

  • In Chapter 11, “Working with Strings,” you'll learn about another method of creating and using strings in C.

  • Alternatively, you can assign a value to a character array using the strncpy()function:

    char name[12];
    strncpy (name, "David Brent", 11);
    
  • The integer version of the name array could be created using this code:

    char name[7] = {65, 117, 98, 114,
     101, 121, 0};
    

    where each letter in Aubrey is represented by its numeric equivalent. See the character table in Appendix B, “Resources,” for the complete list of characters and their associated numeric values.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset