As you know, when we declare an array as
float n[10];
then we have actually declared a total of ten storage locations:
n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]
The lowest index is 0 and the highest index is 9. What do you suppose
will happen if you attempt to access an array location that is not in
the range 1-10? Let's try it out and see what happens.
Read ``examples/array3.c'' into an Emacs buffer, if you haven't done
so already. This is one of the programs that we looked at earlier in
this lesson. Currently, the program prints out an array with the
loop
for (i = 0; i < 10; i = i+1) {
printf("%d\n", n[i]);
}
Change the bounds of the loop so that it reads
for (i = -10; i < 20; i = i+1) {
printf("%d\n", n[i]);
}
Now run the program. What happens?
Click here for the answer
If you access too far beyond the end of an array, something else will
happen. Modify the printing loop so that it reads
for (i = 0; i < 10; i = i+1) {
printf("%d\n", n[i+100000]);
}
What happens when you run it?
Click here for the answer
This situation with array bounds is one of the most unsatisfactory
aspects of C. If you read or write outside of an array's bounds,
you may read or write garbage or (if you are lucky) you
may get a segmentation fault which at least tells you there's a
problem.
In the end, it is up to you to make sure that your program respects
the bounds of its arrays. You'll get very little help from C.
Eric N. Eide
Hamlet Project
Department of Computer Science
University of Utah