|
|
|
|
|
|
|
crash immediately. If you're unlucky, you'll get strange results much later in your program, and you'll have a difficult time figuring out what went wrong. |
|
|
|
|
|
|
|
|
The compiler is like a blind man pacing off the distance from a house. He starts out at the first house, MainStreet[0]. When you ask him to go to the sixth house on Main Street, he says to himself, I must go five more houses. Each house is four big paces. I must go an additional 20 steps. If you ask him to go to MainStreet[100], and Main Street is only 25 houses long, he will pace off 400 steps. Long before he gets there, he will, no doubt, step in front of a moving bus. So be careful where you send him. |
|
|
|
|
|
|
|
|
It is so common to write to one past the end of an array that this bug has its own name. It is called a fence post error. This refers to the problem of counting how many fence posts you need for a 10-foot fence if you need one post for every foot. Most people answer 10, but of course you need 11. Figure 15.2 makes this clear. |
|
|
|
|
|
|
|
|
FIGURE 15.2
Fence post errors. |
|
|
|
|
|
|
|
|
This sort of off by one counting can be the bane of any programmer's life. Over time, however, you'll get used to the idea that a 25-element array counts only to element 24, and that everything counts from 0. (Programmers are often confused why office buildings don't have a floor zero. Indeed, some have been known to push the 4 elevator button when they want to get to the fifth floor.) |
|
|
|
|
|
|
|
|
You can initialize a simple array of built-in types, such as integers and characters, when you first declare the array. After the array name, you put an equal sign (=) and a list of comma-separated values enclosed in braces. For example, |
|
|
|
|
|
|
|
|
int IntegerArray[5] = { 10, 20, 30, 40, 50 }; |
|
|
|
|
|
|
|
|
declares IntegerArray to be an array of five integers. It assigns IntegerArray[0] the value 10, IntegerArray[1] the value 20, and so forth. |
|
|
|
|
|