Download presentation
Presentation is loading. Please wait.
1
Growing Arrays in C Nathan Lee
2
The Problem Compiler statically allocates size, content int a[5];
How do we manipulate the size of arrays in C?
3
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};
4
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; } …
5
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++;
6
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!
7
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
8
Resources Used: Kernighan, Brian W. and Rob Pike. The Practice of Programming Lucent Technologies.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.