teach-ict.com logo

THE education site for computer science and ICT

3. Static arrays

Arrays can hold any number of items. But the data still needs to be stored in memory. This can create problems when the computer doesn't know how much space to assign to an array.

If it assigns too much memory, that's a lot of wasted empty space. If it assigns too little, there might not be enough room to fit all of the needed items.

There are two approaches to setting the length of an array. The first is a static array. Here, the programmer sets in advance how many items can fit into the array, and what type of data it will be storing. The array will not get any bigger or smaller as the program runs.

 

A static array has a defined length which does not change.

You can set the length of a static array when declaring it for the first time. In pseudocode, for example:

                    array byte MyList[5]

This is declaring in the program that the array named MyList requires enough memory to store five items of type 'byte'. Even when it is empty of any elements or values, it is still given the same amount of memory.

Declaring static arrays most of the time is useful to compilers, as it helps the compiler set aside the correct amount of memory in the final executable file. It will also run slightly faster than a dynamic array because there is no need for the program to keep re-calculating storage requirements as that is a fixed value.

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: advantages of a static or dynamic array