Sams Teach Yourself C++ in 21 Days

(singke) #1
Managing Arrays and Strings 413

13


This nasty bug can be very hard to find, because SentinelOne [0]’s value was changed
in a part of the code that was not writing to SentinelOneat all.

Fence Post Errors............................................................................................


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 in 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 13.2 makes this clear.

Note that because all compilers use memory differently, your results might
vary. You might find that the sentinels did not get overwritten. If this is the
case, try changing line 33 to assign yet another value—change the 25 to 26.
This increases the likelihood that you’ll overwrite a sentinel. Of course, you
might overwrite something else or crash your system instead.

NOTE


FIGURE13.2
Fence post errors.


1ft

1234567891011
2ft 3ft 4ft 5ft 6ft 7ft 8ft 9ft 10ft

This type of “off by one” counting can be the bane of any C++ 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.

Some programmers refer to ArrayName[0]as the zeroth element. Getting
into this habit is a mistake. If ArrayName[0]is the zeroth element, what is
ArrayName[1]? The oneth? If so, when you see ArrayName[24], will you real-
ize that it is not the 24th element in the array, but rather the 25th? It is far
less confusing to say that ArrayName[0]is at offset zero and is the first
element.

NOTE


Initializing Arrays ..........................................................................................


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 };
Free download pdf