-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynArray.cpp
48 lines (44 loc) · 1.22 KB
/
DynArray.cpp
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
#include "include/DynArray.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void dynarray_init(DynArray *parr,int initsize){
if(parr != NULL){
parr->data = (void **)malloc(sizeof(char) * initsize);
parr->count = 0;
parr->capacity = initsize;
}
}
void dynarray_free(DynArray *parr){
if(parr == NULL) return;
void **p;
for(p=parr->data;parr->count;--parr->count)
if(*p) free(*p);
free(parr->data);
parr->data = NULL;
}
int dynarray_search(DynArray *parr,int key){
int i;
int **p = (int **)parr->data;
for(i=0;i<parr->count;++i,++p)
if(key==**p) return i;
return -1;
}
void dynarray_realloc(DynArray *parr,int new_size){
int capacity;
void *data;
capacity = parr->capacity;
while(capacity < new_size)
capacity *= 2;
data = realloc(parr->data,capacity);
if(!data) error("memory assign failed!");
parr->capacity = capacity;
parr->data = (void**)data;
}
void dynarray_add(DynArray *parr,void *data){ ///apend ch
int count = parr->count + 1;
if(count * sizeof(void *) > parr->capacity)
dynarray_realloc(parr,count * sizeof(void *));
(parr->data)[count-1] = data;
parr->count = count;
}