Growing Arrays in C Nathan Lee
The Problem Compiler statically allocates size, content int a[5]; How do we manipulate the size of arrays in C?
Adding Values (code) struct Nameval { char *name; int value; }; *found on page 42 of textbook struct Nameval { char *name; int value; }; struct NVtab { int nval; int max; Nameval *nameval; } nvtab; enum { NVINIT = 1, NVGROW = 2};
Adding Values (code) int addname (Nameval newname) { Nameval *nvp; if (nvtab.nameval == NULL) { nvtab.nameval = (Nameval *) malloc (NVINIT * sizeof (Nameval)); if (nvtab.nameval == NULL) return -1; nvtab.max = NVINIT; nvtab.nval = 0; } …
Adding Values (code) …else if (nvtab.nval >= nvtab.max) { nvp = (Nameval *) realloc(nvtab.nameval, (NVGROW*nvtab.max) * sizeof(Nameval)); if (nvp == NULL) return -1; nvtab.max *= NVGROW; nvtab.nameval = nvp; } nvtab.nameval[nvtab.nval] = newname; return nvtab.nval++;
Adding Values realloc doubles the size of the array (performance) Adding 100 elements: growing 100 times vs growing (log2 100 ≈ 7) times ‘nvp’ is a temp value – if realloc fails Not Sorted!
The Bottom Line Arrays are good for static, non-sorted allocation We can minimize the cost of allocation in some ways For fluctuating values and contents, don’t use arrays
Resources Used: Kernighan, Brian W. and Rob Pike. The Practice of Programming. 1999 Lucent Technologies.