Presentation is loading. Please wait.

Presentation is loading. Please wait.

Growing Arrays in C Russell Stephens.

Similar presentations


Presentation on theme: "Growing Arrays in C Russell Stephens."— Presentation transcript:

1 Growing Arrays in C Russell Stephens

2 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

3 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;

4 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

5 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]

6 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

7 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

8 Source Kernighan, Brian W. and Rob Pike. The Practice of Programming Lucent Technologies.


Download ppt "Growing Arrays in C Russell Stephens."

Similar presentations


Ads by Google