130 likes | 387 Views
Growing Arrays in C Language. Do not use Growing Sorted Array O(n 2 ) Operation Avoid when n is large. Use Keep track of a variable Few items. When to Use. Java and C++ Library Class C struct. Code Allocate Memory malloc realloc Minimize Memory Space Resize in chunks
E N D
Do not use Growing Sorted Array O(n2) Operation Avoid when n is large Use Keep track of a variable Few items When to Use
Java and C++ Library Class C struct Code Allocate Memory malloc realloc Minimize Memory Space Resize in chunks Gather Array Together Theory of Growing Arrays
Memory Allocation • Library function - malloc() • malloc() allocates certain size of bytes in memory • malloc() returns a pointer to the allocated space or NULL if there is an error or size is zero • Memory allocated by function must be released or freed when finished • void *malloc()(size_t size) • void free(void *pointer)
Example int *ptr = malloc(10*sizeof(int)); if (ptr == NULL) { /*Error Occurred. Do Something*/ } else { free(ptr); ptr = NULL; }
Reallocation of Memory • Library Function - realloc() • realloc() changes the size of a block of memory already allocated by malloc() • realloc() returns a pointer to block of memory or NULL • May expand or move block of memory • void *realloc(void *ptr, size_t size)
Example int *ptr = malloc(10*sizeof(int)); /*Somewhere Later in the Program*/ int *temp = realloc(ptr, 15*sizeof(int)); if (temp == NULL) { /*Error Occurred. Do Something*/ } else { ptr = temp; }
Growing Array Code (1) typedef struct Nameval Nameval; struct Nameval{ char *name; int value; }; struct NVtab{ int nval; /*current # of values*/ int max; /*allocated # of values*/ Nameval *nameval; /*array of pairs*/ } nvtab; enum{NVINIT = 1, NVGROW = 2};
Growing Array Code (2) int addname(Nameval newname) { Nameval *nvp; if (nvtab.nameval == NULL) nvtab.nameval = (Nameval *) malloc(NVIT*sizeof(Nameval)); if (nvtab.nameval == NULL) return -1; nvtab.max = NVINIT; nvtab.nval = 0; }
Growing Array Code (3) 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++; }
memmove() Function • To shrink a growing array we need to use memmove() • memmove() copies n bytes from one location and moves it to another • *memmove(*s1, const *s2, size_t n)
Shrinking Array Code int delname(char *name) { int i; for (i = 0; i < nvtab.nval; i++) if (strcmp(nvtab.nameval[i].name, name) == 0){ memmove(nvtab.nameval+i,nvtab.nameval+i+1, (nvtab.nval-(i+1))*sizeof(Nameval)); nvtab.nval--; return 1; } return 0; }