C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
Yes, this is a little tedious. You might have to read this section again later after you get
more comfortable with pointers and arrays.

If you want to have the advantage of a character pointer—that is, if you want to be able to assign
string literals to the pointer and still have the safety of arrays so you can use the character pointer to
get user input—you can do so with a little trick.


If you want to store user input in a string pointed to by a pointer, first reserve enough storage for that
input string. The easiest way to do this is to reserve a character array and then assign a character
pointer to the beginning element of that array:


Click here to view code image


char input[81]; // Holds a string as long as 80 characters
char *iptr = input; // Also could have done char *iptr = &input[0]

Now you can input a string by using the pointer as long as the string entered by the user is not longer
than 81 bytes long:


Click here to view code image


gets(iptr); /* Makes sure that iptr points to the string typed by
the user */

You can use a nice string-input function to ensure that entered strings don’t get longer than 81
characters, including the null zero. Use fgets() if you want to limit the number of characters
accepted from the user. fgets() works like gets(), except that you specify a length argument.
The following statement shows fgets() in action:


Click here to view code image


fgets(iptr, 81, stdin); /*Gets up to 80 chars and adds null zero */

The second value is the maximum number of characters you want to save from the user’s input.
Always leave one for the string’s null zero. The pointer iptr can point to a string as long as 81
characters. If the user enters a string less than 81 characters, iptr points to that string with no
problem. However, if the user goes wild and enters a string 200 characters long, iptr points only to
the first 80, followed by a null zero at the 81st position that fgets() added, and the rest of the
user’s input is ignored.


Tip

You can use fgets() to read strings from data files. The third value of fgets()
can be a disk file pointer, but you’ll learn about disk pointers later in the book. For
now, use stdin as the third value you send to fgets() so that fgets() goes to
the keyboard for input and not somewhere else.

You also can assign the pointer string literals using the assignment like this:


iptr = "Mary Jayne Norman";
Free download pdf