Download presentation
Presentation is loading. Please wait.
1
Tim Ehrlich Growing Arrays in C
2
Other structures: Previously seen/used arrays have been static.
Size and contents of the array are set when the program is compiled, and cannot be changed. Hash tables are more appropriate for larger, modifiable data structures.
3
Considerations: Adding elements to a sorted array takes n2 time.
Large values of n will take exponentially longer to add, making it unattractive. For a small number of variables, a growing array is appropriate. Resizing the array in set chunks can reduce allocation cost in terms of time and space. Growing array elements must be called by subscripts, not pointers, since the array address can change upon resize.
4
Code, pg. 42 Growing the array by a factor of 2 (doubling it) provides a simple and fast way of changing its size. Growing an array will preserve the elements already in the array, and will also keep them if the grow fails. In this example, items are added to the end of the array, and the array is automatically grown if necessary. An error will be returned if the grow fails (out of memory or other error).
5
Code, pg. 43 You can delete an element from any position in the array, but the program has to handle filling that gap This program will move the elements down 1 by 1 to fill the gap, which will preserve the element’s order. C contains functions for moving memory Memcpy is faster, but overwrites if source and destination overlap Memmove is slower, but will always be correct (most often used)
6
Code, pg. 44 Memmove Memmove(s1, s2, size n)
Will copy n bytes from location defined by s2 to location defined by s1 Operates as if s2 is first copied to temporary array, then from there to s1. a, b, c, _, e, f, g Memmove(4, 5, 3) a, b, c, e, f, g, _
7
Memmove Avoids copying elements in wrong order
Deleting: start at beginning and move elements down Inserting: start at end and move elements up A for loop would require remembering to increment or decrement appropriately. Memmove you simply define the starting and ending location, and it will know to do the appropriate operation to avoid overwriting data.
8
Deletion alternatives
Mark elements unused Set value to null Search for null value in array first and add new element there, otherwise add to end (does not preserve order) Leave null gaps in arrays (not a good practice, but occasionally has a use) Pull element off end of array and move single element into deleted slot. (does not preserve order)
9
Recap For small or fixed-size sets of data, arrays are more functional and more efficient than other structures. Arrays provide fast access to data, and better support quick sorting or binary search, etc. They also have minimal overhead requirements. Maintaining changing values is where arrays get “expensive”, so if the size of the array is unknown, or could be / become large, other structures are better.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.