- The gets()function accepts input from the keyboard until it reaches a newline
character. - The string entered, minus the new line and with a trailing null character, is stored
in the memory location pointed to by input. - The address of the string (the same value as input) is returned to the pointer ptr.
- An assignment statementis an expression that evaluates to the value of the variable
on the left side of the assignment operator. Therefore, the entire expression ptr =
gets(input)evaluates to the value of ptr. By enclosing this expression in paren-
theses and preceding it with the indirection operator (*), you obtain the value
stored at the pointed-to address. This is, of course, the first character of the input
string.
5.NULLis a symbolic constant defined in the header file stdio.h. It has the value of the
null character ( 0 ). - If the first character of the input string isn’t the null character (if a blank line hasn’t
been entered), the comparison operator returns true, and the whileloop executes.
If the first character is the null character (if a blank line has been entered), the
comparison operator returns false, and the whileloop terminates.
When you use gets()or any other function that stores data using a pointer, be sure that
the pointer points to allocated space. It’s easy to make a mistake such as this:
char *ptr;
gets(ptr);
The pointer ptrhas been declared but not initialized. It points somewhere, but you don’t
know where. The gets()function doesn’t know that ptrhasn’t been initialized to point
somewhere, so it simply goes ahead and stores the entered string at whatever address is
contained in ptr. The string might overwrite something important, such as program code
or the operating system. Most compilers won’t catch this type of mistakes, so you, the
programmer, must be vigilant.
240 Day 10
FIGURE10.1
The components of a
whilestatement that
tests for input of a
blank line.
4
while ( *( ptr = gets(input)) != NULL)
31265
17 448201x-CH10 8/13/02 11:17 AM Page 240