src/string_list.c

changeset 102
665b60727a89
parent 101
0cb645809b1a
child 103
31fa205db85a
equal deleted inserted replaced
101:0cb645809b1a 102:665b60727a89
26 26
27 #include "string_list.h" 27 #include "string_list.h"
28 28
29 #include <assert.h> 29 #include <assert.h>
30 30
31 static void do_not_free(void* item) { 31 static void do_not_free(void *item) {
32 (void) item; /* do not do anything with the item */ 32 (void) item; /* do not do anything with the item */
33 } 33 }
34 34
35 string_list* new_string_list() { 35 string_list *new_string_list() {
36 string_list* stringList = malloc(sizeof(string_list)); 36 string_list *stringList = malloc(sizeof(string_list));
37 stringList->count = 0; 37 stringList->count = 0;
38 stringList->capacity = 32; 38 stringList->capacity = 32;
39 stringList->items = calloc(stringList->capacity, sizeof(char*)); 39 stringList->items = calloc(stringList->capacity, sizeof(char*));
40 stringList->free_item = do_not_free; 40 stringList->free_item = do_not_free;
41 41
42 return stringList; 42 return stringList;
43 } 43 }
44 44
45 void destroy_string_list(string_list* list) { 45 void destroy_string_list(string_list *list) {
46 if (list) { 46 if (list) {
47 if (list->items) { 47 if (list->items) {
48 for (size_t i = 0 ; i < list->count ; i++) { 48 for (size_t i = 0 ; i < list->count ; i++) {
49 list->free_item(list->items[i]); 49 list->free_item(list->items[i]);
50 } 50 }
52 } 52 }
53 free(list); 53 free(list);
54 } 54 }
55 } 55 }
56 56
57 void add_string(string_list* list, char* item) { 57 void add_string(string_list *list, char *item) {
58 assert(list != NULL); 58 assert(list != NULL);
59 if (list->count < list->capacity) { 59 if (list->count < list->capacity) {
60 list->items[list->count++] = item; 60 list->items[list->count++] = item;
61 return; 61 return;
62 } 62 }
63 size_t newCapacity = list->capacity * 2; 63 size_t newCapacity = list->capacity * 2;
64 char** reallocated_list = 64 char **reallocated_list =
65 realloc(list->items, sizeof(char*) * newCapacity); 65 realloc(list->items, sizeof(char*) * newCapacity);
66 assert(reallocated_list != NULL); 66 assert(reallocated_list != NULL);
67 list->capacity = newCapacity; 67 list->capacity = newCapacity;
68 list->items = reallocated_list; 68 list->items = reallocated_list;
69 list->items[list->count++] = item; 69 list->items[list->count++] = item;

mercurial