Repository navigation
Expand file tree
/
Copy patharray.c
More file actions
116 lines (98 loc) · 2.36 KB
/
Copy patharray.c
File metadata and controls
116 lines (98 loc) · 2.36 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* bigarray.c
Implementation of a resizable array, for lab 6
*/
#include <stdlib.h>
#include "array.h"
#define INITIAL_SIZE 10
typedef struct array_record {
cast_member** mem; // an array of pointers to cast_members
int size;
int num_elements;
} array_record;
// internal helper function:
// double the size of the memory storage backing an array
void grow(array arr)
{
arr->size *= 2;
cast_member** new_mem = malloc(sizeof(cast_member*) * arr->size);
for(int i = 0; i < arr->num_elements; i++)
{
new_mem[i] = arr->mem[i];
}
free(arr->mem);
arr->mem = new_mem;
}
// internal helper function
// return the greater of two numbers
int max(int a, int b)
{
return a > b ? a : b;
}
// create a new, empty array, with an initial size of 10 but no elements
array array_new()
{
array arr = malloc(sizeof(array_record));
arr->mem = malloc(sizeof(cast_member*) * INITIAL_SIZE);
arr->size = INITIAL_SIZE;
arr->num_elements = 0;
return arr;
}
// add a new element to the end of the array
void array_add(array arr, cast_member* new_elt)
{
array_add_at(arr, arr->num_elements, new_elt);
}
// access an element in the array. Returns NULL if the index is out of range.
cast_member* array_get(array arr, int index)
{
if(index >= 0 && index < arr->num_elements)
{
return arr->mem[index];
}
else
{
return NULL;
}
}
// change an element in the array.
void array_set(array arr, int index, cast_member* new_val)
{
if(index >= arr->num_elements)
{
array_add_at(arr, index, new_val);
}
else
{
arr->mem[index] = new_val;
}
}
// returns the number of elements in an array
int array_size(array arr)
{
return arr->num_elements;
}
// release the memory used for this array
void array_free(array arr)
{
free(arr->mem);
free(arr);
}
// adds an element at the given (non-negative) index, enlarging the array
// and shifting elements to the right to make it fit
void array_add_at(array arr, int index, cast_member* new_elt)
{
while(arr->num_elements == arr->size || index >= arr->size) // we will need to grow
{
grow(arr);
}
if(index < arr->size) // do we have the memory already?
{
// move any necessary elements out of the way
for(int i = arr->num_elements; i > index; i--)
{
arr->mem[i] = arr->mem[i-1];
}
arr->mem[index] = new_elt;
}
arr->num_elements = max(index + 1, arr->num_elements + 1);
}