The ASCII-Zero Character Array - dummies

By Stephen R. Davis

Arrays in C++ have an inherent problem: You can never know, just by looking at the array, how many values are actually stored in it. Knowing the size of an array is not enough. That tells you how many values the array can hold, not how many it actually does hold.

The difference is like the difference between how much gas your car’s tank can hold and how much gas it actually has. Even if your tank holds 20 gallons, you still need a gas gauge to tell you how much is in it.

There are essentially two ways of keeping track of the amount of data in an array:

  • Keep a count of the number of values in a separateintvariable. This is the technique used by the ArrayDemo program. The code that reads the user input keeps track of the number of entries in nCount. The only problem is that the program has to pass nCount along to every function to which it has passed the nScores array. The array isn’t useful without knowledge of how many values it stores.

  • Use a special value in the array as an indicator of the last element used. By convention, this is the technique used for character arrays in C++.

One ASCII character in particular is not a legal character: ‘’. This character is also known as the null character. It’s the character with a numerical value of zero. A program can use the null character as the end of a string of characters.

The null character has no purpose other than signaling the end of a character array. The user can never enter a null character. This means that you don’t have to pass a separate count variable around — you can always tell the end of the string by looking for a null.

The designers of C and C++ liked this feature so well that they settled on it as the standard for character strings. They even gave it a name: the ASCII-zero array or ASCIIZ for short.

The null character has another advantageous property. It is the only character whose value is considered false in a comparison expression (such as in a loop or an if statement).

Remember that 0 or null is considered false. All other values evaluate to true. This makes writing loops that manipulate ASCIIZ strings even easier.