-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamicarray.c
60 lines (53 loc) · 1.72 KB
/
dynamicarray.c
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "dynamicarray.h"
DynamicArray* make_array(size_t maxelements) {
DynamicArray* new_array = (DynamicArray*) malloc(sizeof(DynamicArray));
try
{
new_array->data = malloc(maxelements);
new_array->size = 0;
new_array->maxelements = maxelements;
if(new_array == NULL || new_array->data == NULL) throw();
} catch{
error("DA", "Caught an exception while allocating an array!");
}
return new_array;
}
void free_array(DynamicArray* array){
free(array->data);
free(array);
}
void append_array(DynamicArray* array, void* element, size_t size){
try
{
if (array->size >= array->maxelements) {
array->maxelements *= 2;
array->data = realloc(array->data, array->maxelements * size);
}
memcpy((char *) array->data + (array->size * size), element, size);
if(array == NULL || array->data == NULL) throw();
array->size++;
} catch{
error("DA", "Caught an exception while allocating a data to an array!");
}
}
char* array_toString(DynamicArray* array) {
try
{
if (array == NULL || array->data == NULL || array->size == 0)throw();
size_t str_size = array->size * 12 + 2;
char* result = (char*) malloc(str_size);
strcpy(result, "[");
for (size_t i = 0; i < array->size; i++) {
char buffer[12];
sprintf(buffer, "%d", ((int *) array->data)[i]);
strcat(result, buffer);
if (i < array->size - 1)
strcat(result, ", ");
}
strcat(result, "]");
return result;
} catch{
error("DA", "converting an array to a string resulted in an error.");
return "[]";
}
}