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

(Romina) #1
Tip

Printing strings in arrays is easy. You use the %s conversion character:
Click here to view code image
printf("The month is %s", month);

If you define an array and initialize the array at the same time, you don’t have to put the number in
brackets. Both of the following do exactly the same thing:


char month[8] = "January";
char month[] = "January";

In the second example, C counts the number of characters in January and adds one for the null zero.
You can’t store a string larger than eight characters later, however. If you want to define a string’s
character array and initialize it but leave extra padding for a longer string later, you would do this:


Click here to view code image


char month[25] = "January"; /* Leaves room for longer strings */

Initializing Strings


You don’t want to initialize a string one character at a time, as done in the preceding section.
However, unlike with regular nonarray variables, you can’t assign a new string to the array like this:


Click here to view code image


month = "April"; /* NOT allowed */

You can assign a string to a month with the equals sign only at the time you define the string. If later
in the program you want to put a new string into the array, you must either assign it one character at a
time or use C’s strcpy() (string copy) function that comes with your C compiler. The following
statement assigns a new string to the month:


Click here to view code image


strcpy(month, "April"); /* Puts new string in month array */

Note

In your programs that use strcpy(), you must put this line after the #include
<stdio.h>:
#include <string.h>
Free download pdf