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

(Romina) #1
Warning

The second string’s length doesn’t end at the 0 in 10 because the 0 in 10 isn’t a null
zero; it’s a character zero.

Tip

All single characters of data have a length of 1. Therefore, both 'X' and "X" have
lengths of one, but the "X" consumes two characters of memory because of its null
zero. Any time you see a string literal enclosed in quotation marks (as they all must
be), picture in your mind that terminating null zero at the end of that string in memory.

Character Arrays: Lists of Characters


Character arrays hold strings in memory. An array is a special type of variable that you’ll hear much
more about in upcoming chapters. All the data types—int, float, char, and the rest—have
corresponding array types. An array is nothing more than a list of variables of the same data type.


Before you use a character array to hold a string, you must tell C that you need a character array in the
same place you would tell C that you need any other kind of variable. Use brackets ([ and ]) after the
array name, along with a number indicating the maximum number of characters the string will hold.


An example is worth a thousand words. If you needed a place to hold month names, you could define
a character array called month like this:


Click here to view code image


char month[10]; /* Defines a character array */

Tip

Array definitions are easy. Take away the 10 and the brackets, and you have a regular
character variable. Adding the brackets with the 10 tells C that you need 10 character
variables, each following the other in a list named month.

The reason 10 was used when defining the array is that the longest month name, September, has
nine characters. The tenth character is for, you guessed it, the null zero.


Tip
Free download pdf