[CSI] Array Size

Mikhail Nesterenko mikhail at cs.kent.edu
Sun Oct 2 11:19:21 EDT 2016


> Oh... I see. I had been thinking that you could iterate through the
> elements until there weren't any and return that count. Does this
> have to
> do with the range checking concept you mentioned?
>
> int myArray[5] = { 2, 3, 4, 5, 6 };
> int countIndex = 0;
>
> while ( myArray[countIndex] *exists *)
>     ++countIndex;
>
> In this instance if there was a way to test if myArray[] didn't exist,
> countIndex should end up as 5. But there's no *exists* function, is there?
>

ARRAY SIZE

For (raw) arrays that we studied, iteration over elements without
knowing size is not possible. The size has to be stored in a separate
variable. So the above example should be coded as follows:

    const int size = 5;
    int myArray[5] = { 2, 3, 4, 5, 6 };
    for(int countIndex=0; countIndex < size; ++countIndex)
       // do something with element myArray[countIndex]


There is a construct called range-based-for (studied in CSIII) that
allows iteration over (raw) array without explicitly stating its
size. There are also vectors (studied in CSIB) whose size can be found
out with a function.


RANGE CHECK

In C++, array index is not checked for range, and may lead to
out-of-range error run-time error. For example

    myArray[55] = 22;

will compile and run. Visual Studio compiler, in debug mode,
compiles range checking for every array access. That is, the above
statement would be compiled into something like this:

    if 55 is less than 0 or greater than 5 then abort program execution
    myarray[55] = 22;

This leads to a visible run-time-notification rather than (possibly
hidden) memory corruption. 

Thanks,
--
Mikhail


More information about the cs13001 mailing list