- It is now the time to discuss some rules
for using an array, which will save you
a lot of time and headaches later.
The number one rule about arrays is
to watch the index.
It's the pitfall in so many instances
that you really have to be very careful
and instill this into any practice.
They're a very simple rule, actually:
The index must be within the range of the array.
It always starts at zero and it ends
at the length of the array minus one.
So if you have an array of five elements,
the index runs from zero to four.
Let's look at an array that's initialized
with those numbers for a length of five.
And let's set up a number to zero.
I want to update list[k], which is zero,
and add two to it.
This means the first element in the array
at position zero, 23, has now become 25.
So far, so good.
Now I'm going to set k to five.
Now recall there's only five elements
in the array, which means the last position is four.
I'm now attempting to add one
to the value stored at position five.
What do you think might happen?
You have to remember a second thing about C:
The compiler assumes you know what you're doing.
When you are manipulating the array,
you have to be extremely careful because
you may do things that are incorrect,
but the compiler will not tell you.
And let's see this in action.
I copy the same exact code from the previous screen
into the C program here.
Very simple program, which is going to bring three things:
The third element, the sixth element,
and the twentieth element of an array
that only has five positions.
First of all, let's compile this.
I'm going to build the project to compile it.
And notice, there are no error messages.
So the fact that I'm attempting in line 23
to print a number that doesn't exist,
as well as in line 22, which lists five's position
in the array, it doesn't generate an error.
Compiler assumes you know what you're doing.
Let's see what happens when I'm running this program.
It tells me the third element is 15,
which is correct.
Zero, one, two, which means elements one, two and three.
That is correct.
The sixth element is one.
There is no sixth element defined in the array.
There's only five of them.
Where does this one come from?
The twentieth element is 32,767.
If you inadvertently access or try to access
a location in an array that doesn't exist,
the results are unpredictable.
It may range between getting an erroneous result
in a calculation to crashing something,
to coming up with completely ridiculous outcome
in a program.
And this is all because there are no errors
and they assume that everything is okay.
There is one thing that the compiler might do for you.
Sometimes, it might issue some warnings.
In this case, there are no warning issues,
so you are completely on your own.
Again, remember to always use an index
within the range of the array.
It is up to you to manage the values
of those indexes correctly to avoid situations like that.