Problems with Arrays
Space Issues !
Arrays have a fixed size
- At first we hard-coded the size of the array when we
declared it. Remember int array[10]; ? But we
found that this made our code be much too specific and limited.
To reuse our code with a different size array, we'd have to
replace the number 10 everywhere it appeared within the program
with the new size.
- Then we discovered #define. We could #define SIZE 10
This made life easier, since to make the same code work with a
different size array, there was only one line of code to change, the
#define. We still found that this was severely limiting. We had to
guess a size that we hoped would be adequate. We had to check to make
sure that we weren't overrunning the end of the array. If the size we
guessed was too small we had to terminate the program.
- Then we discovered malloc. At last we can make an array
be any size we want by allocating the space needed to store it
dynamically. We could ask the user how big the array was going to
be and allocate the space using malloc. What if the user guesses,
and he guesses too small ? We'll have to abort. - OR - we could
allocate a larger space and copy the current contents into the
larger array. This is risky, we might just run out of memory.
Arrays must be held in contiguous space
- Arrays must have contiguous space to hold the elements.
There might be plenty of room to hold the information that needs
to be held, but there may not be one block of contiguous space
big enough to do so.