-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamicarray.c
More file actions
46 lines (43 loc) · 1.23 KB
/
dynamicarray.c
File metadata and controls
46 lines (43 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// Created by s184805 on 14-10-2019.
//
#include <stdlib.h>
#include <string.h>
#include "dynamicarray.h"
void initArray(Array *a, unsigned long int initialSize, unsigned long int stringsize) {
char * e = "test";
a->array = (char **)calloc(initialSize, sizeof(&e));
a->used = 0;
a->size = initialSize;
a->strsize = stringsize;
}
void addString(Array *a, char *element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
char * e = "test";
a->size *= 2;
a->array = (char **)realloc(a->array, a->size * sizeof(&e));
}
a->array[a->used++] = element;
}
int contains(Array* a, char * element)
{
for (unsigned long int i = 0; i < a->used; i++){
if(strcmp(element, a->array[i]) == 0){
return 1;
}
}
return 0;
}
void freeArray(Array *a) {
//first free every string in the array.
for (unsigned long int i = 0; i < a->size; i++){
char * str = *(a->array+i);
free(str);
}
//then free the array of strings.
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}