Growing Arrays in C Russell Stephens
O- Notation Notation Name Example O(1) Constant Array index O(log n) Logarithmic Binary search O(n) Linear String comparison O(n log n) N log n Quicksort O(n2) Quadratic Simple sorting O(n3) Cubic Matrix multiplication O(2n) Exponential Set partioning
Maintaining Arrays Cost of allocation can be minimized by resizing the array in chunks Arrays should be gathered together in structs typedef struct Nameval Nameval; struct Nameval { char *name; int value; }; Struct Nvtab { int nval; int max; Nameval *nameval; } nvtab;
Growing Arrays nvp = (Nameval *) realloc(nvtab.nameval, (NVGROW*nvtab.max) * sizeof(Nameval)); Realloc grows the array to the current size, and protects the existing elements
Realloc Function Using the realloc function reallocates the memory addresses of the members in the array Because of this, pointers cannot be used to access members of the array Instead of pointers you must used subscripts to access members of the array Array[index]
memmove vs memcpy memmove memcpy memmove is always correct memmove should always be used over memcpy memcpy is very fast but not always correct Memcpy can overwrite memory locations if a source and destination overlap
Summary Arrays are a simple way to group data Arrays can provide O(1) access to data Arrays with a large value of n can be expensive to use and alternates should be used
Source Kernighan, Brian W. and Rob Pike. The Practice of Programming. 1999 Lucent Technologies.