-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynarray.c
76 lines (64 loc) · 1.31 KB
/
dynarray.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ELETYPE int
ELETYPE *ar;
unsigned size;
unsigned num;
unsigned growby;
void init_array(unsigned asize, unsigned agrowby)
{
size = asize;
growby = agrowby;
num = 0;
ar = (ELETYPE *)malloc(size * sizeof(ELETYPE));
}
void insert(int idx, ELETYPE value)
{
unsigned need;
need = num + 1;
if(need > size) {
size = need + growby;
ar = (ELETYPE *)realloc(ar, size * sizeof(ELETYPE));
}
memmove(ar + idx + 1, ar + idx, (num - idx)*sizeof(ELETYPE));
ar[idx] = value;
num++;
}
void delete(int idx)
{
memmove(ar + idx, ar + idx + 1, (num - idx - 1)*sizeof(ELETYPE));
num--;
}
void append(ELETYPE value)
{
insert(num, value);
}
void uninit_array()
{
free(ar);
}
void dump_array(char *s_mark)
{
unsigned i;
printf("%16s => size=%02d, num=%02d : ", s_mark, size, num);
for(i = 0; i < num; i++) {
printf("%2d ", ar[i]);
}
printf("\n");
}
int main()
{
int i;
init_array(10, 5); dump_array("initial");
for(i = 1; i <= 8; i++) {
append(i);
}
dump_array("append 8");
insert(3, 10); dump_array("insert 10");
insert(3, 11); dump_array("insert 11");
insert(3, 12); dump_array("insert 12");
delete(7); dump_array("delete 7");
uninit_array();
return 0;
}