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

(Romina) #1

right in the printf() statements? Again, the value of these variables will become more apparent
after Chapter 8, “Interacting with Users,” when you learn to get information from users.


You were already using #include to add the <stdio.h> file to all your programs that use
printf() (as well as other common functions that you will soon be adding to your programming
toolbox). Now you have a second header file, <string.h>, to #include as well. The next
chapter covers #include in more detail.


To remind you of the different methods of declaring and initializing string variables, the kid and
hero variables are each defined differently. For a fun exercise, comment out the strcpy line to see
what your program prints on the screen when Hero3 is used in a printf() without having been
initialized. My output was a bizarre collection of characters—those were already sitting in the space
that became that variable, so if you don’t put anything in it, you’ll get whatever is there now.


The Absolute Minimum
If you need to store words, you need to use character arrays; C does not support a
string data type. Key points from this chapter include:


  • Store strings in character arrays, but reserve enough array elements to hold the
    longest string you’ll ever store in that array.

  • Don’t forget that strings must end with a terminating zero.

  • When writing to your array, remember that the subscripts begin at 0 , not 1.

  • There are three ways to place a string in a character array: You can initialize it at
    the time you define the array, you can assign one element at a time, or you can use
    the strcpy() function.

  • If you use the strcpy() function in your programs, remember to add #include to the beginning of your program.

Free download pdf