Let's take a look at a simple application of arrays of characters:
#include <stdio.h> main() { char name[40] ; printf( "What is your name? " ) ; scanf( "%s", name ) ; printf( "Hello, %s, nice to meet you.\n", name ) ; }
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.
scanf()
and the printf()
,
we use a new format specifier, %s
, to indicate that we're
operating on a string.
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.
%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,
main() { 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 ) ; }
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.
name
is an array
of characters.