Stringing Letters Together

So far we have looked mainly at integer arrays (and the question in Part 5-1 looked at a floating point array). We can, however, have arrays of anything we want. One particularly useful type of array is the array of characters. It is so useful that we give it it's own name, the string, and we have a library just for strings.

Let's take a look at a simple application of arrays of characters:

#include <stdio.h>

   char name[40] ;

   printf( "What is your name? " ) ;
   scanf( "%s", name ) ;
   printf( "Hello, %s, nice to meet you.\n", name ) ;

  1. The array name is declared using the same syntax as we've used for other arrays. We've just said that it's an array of characters instead of an array of integers.
  2. In both the scanf() and the printf(), we use a new format specifier, %s, to indicate that we're operating on a string.
  3. When doing a scanf() to read a string, we don't put the ampersand (&) before the array name. Remember, we always put the ampersand before the variables we read using scanf(). The reason for this distinction is given later.
We just also point out another thing about using %s in a scanf(). It will read only up to a space or newline. So we cannot read a person's full name here if we use a space to separate the two names. While there are ways of dealing with this limitation and which allow us to read strings that contain spaces, they involve subtleties of scanf() and the standard I/O library. We'll restrict our attention to dealing with one name at a time. For example,

   char first[40], last[40] ;

   printf( "What is your name (first last)? " ) ;
   scanf( "%s%s", first, last ) ;
   printf( "Hello, %s %s, nice to meet you.\n", first, last ) ;

could be used to process a person's first and last name. (Of course, now we can't deal with a middle name or initial, but nobody's perfect.)

Before we wrap up this initial look at strings, there's one additional facet of them that we need to examine. Certainly it would be rare for a person to have 40 letters in their first or last name. But nowhere are we explicitly representing how many characters we have as we did with the number of students or grades. We don't need to because scanf(), printf() and all other functions that deal with strings expect the length of a string to be represented implicitly with itself. This is done by placing the null byte at the end of the string. The null byte is represented by the special character '\0'. Since we have to have a byte to store the null byte, a string which is allocated to be 40 characters long only has room to store 39 characters. Keep this in mind as you declare arrays to hold strings.

Which statements are valid if name is an array of characters.

scanf( "%s", name ) ;
scanf( "%s", &name ) ;
name[5] = 'a' ;
name[5] = '\n' ;
name = "Me" ;