Sams Teach Yourself C in 21 Days

(singke) #1
apple
dog
merry
program
zoo
It will be worthwhile for you to examine some of the details of this program.
Several new library functions are used for various types of string manipulation.
They are explained briefly here and in more detail on Day 17, “Manipulating Strings.”
The header file string.h must be included in a program that uses these functions.
In the get_lines()function, input is controlled by the whilestatement on lines 41 and
42, which read as follows (condensed here onto one line):
while ((n < MAXLINES) && (gets(buffer) != 0) && (buffer[0] != ‘\0’))
The condition tested by the whilehas three parts. The first part,n < MAXLINES, ensures
that the maximum number of lines has not been input yet. The second part,
gets(buffer) != 0, calls the gets()library function to read a line from the keyboard
intobufferand verifies that end-of-file or some other error has not occurred. The third
part,buffer[0] != ‘\0’, verifies that the first character of the line just input is not the
null character, which would signal that a blank line had been entered.
If any of these three conditions isn’t satisfied, the whileloop terminates, and execution
returns to the calling program, with the number of lines entered as the return value. If all
three conditions are satisfied, the following ifstatement on line 44 is executed:
if ((lines[n] = (char *)malloc(strlen(buffer)+1)) == NULL)
This statement calls malloc()to allocate space for the string that was just input. The
strlen()function returns the length of the string passed as an argument; the value is
incremented by 1 so that malloc()allocates space for the string plus its terminating null
character. The (char *), just before malloc()on line 44, is a typecastthat specifies the
type of pointer to be returned by malloc(), in this case a pointer to type char. You’ll
learn more about typecasts on Day 20.
The library function malloc(), you might remember, returns a pointer. The statement
assigns the value of the pointer returned by malloc()to the corresponding element of
the array of pointers. If malloc()returnsNULL, theifloop returns execution to the call-
ing program with a return value of -1. The code in main()tests the return value of
get_lines()and checks whether a value less than zero is returned; lines 23 through 27
report a memory allocation error and terminate the program.
If the memory allocation was successful, the program uses the strcpy()function on line
46 to copy the string from the temporary storage location bufferto the storage space
just allocated by malloc(). The whileloop then repeats, getting another line of input.

404 Day 15

ANALYSIS

25 448201x-CH15 8/13/02 11:13 AM Page 404

Free download pdf