preview

Smartarray Essay

Decent Essays

#include #include #include #include "SmartArray.h" // this creates a smart array pointer // our code should create an array that dynamically increases or decreases SmartArray *createSmartArray(int length) { int n=0, i, capacity; // Dynamically allocate space for a new SmartArray SmartArray *smarty; char **temp; temp = NULL; smarty = malloc(sizeof(SmartArray)); if(smarty==NULL) return NULL; smarty->size = 0; // Initialize its internal array to be of length length or // DEFAULT_INIT_LEN if(length DEFAULT_INIT_LEN ) { temp = malloc(sizeof(char * ) * length); n = length; } smarty->capacity = n; if (temp == NULL) return NULL; smarty->array=temp; // initialize pointers in the array to NULL for (i=0; iarray[i] = NULL; …show more content…

LL; if(str==NULL) return NULL; size = smarty->size; capacity = smarty->capacity; slen = strlen(str); // expands the array if full // but really just creates an array of capacity*2 +1 and destroys old if (size==capacity) { expandSmartArray( smarty, (capacity * 2 + 1)); } tempVar = malloc(sizeof(char) * (slen+1)); if(tempVar==NULL) return NULL; strcpy(tempVar, str); smarty->array[size] = tempVar; if (str== NULL||smarty->array== NULL||smarty==NULL) return NULL; smarty->size = size + 1; // return the contents of string pointer return smarty->array[size]; } // expands smartArray to size of length SmartArray *expandSmartArray(SmartArray *smarty, int length) { int i, cap, si; char **tempArray; if(smarty==NULL) return NULL; if(smarty->array==NULL) return NULL; tempArray=NULL; si = smarty->size; cap = smarty->capacity; if(length array[i]; } for (i=si; iarray); // copies the temp array address to the old array smarty->array = tempArray; smarty->capacity = length; printf("-> Expanded SmartArray to size %d.\n", length); } else { return NULL; } return smarty; } // returns the element at the index // this function protects the user from going out of bounds with the array char *get(SmartArray *smarty, int index) { // if index was out of bounds or if the smarty pointer was null if((index < 0) || (index > smarty->capacity)|| smarty==NULL) return NULL; return smarty->array[index]; } // sets a string at the index indicated // if no

Get Access