Regardless of whether elements have default values, the difficulty is
the reallocation of memory. In C, we can use the subroutine
malloc
to request memory. When an array increases in size, we
allocate for a new and bigger array, copy everything from the
existing array, then free
the existing array.
This also means that resizing is an expensive operation. It is expensive because of all the data copying. An even more important impact of frequent resizing is memory fragmentation. Memory fragmentation occurs when memory chunks of different sizes are allocated and deallocated frequently.
One approach to resize an array is to always double the capacity when needed. Some approaches also shrinks the capacity of an array by half when it is okay to do so. The following is a sample verbal log of how an array adjusts its capacity:
Besides doubling/halfing, there are other techniques to change the capacity of an array. Such techniques include the use of linked lists, trees and maps. However, these techniques are quite advanced compared to the intended level of skills for this module.
Copyright © 2006-09-13 by Tak Auyeung