-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathint_array.c
64 lines (52 loc) · 1.29 KB
/
int_array.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
#include <stdio.h>
typedef struct int_array {
int capacity;
int* data;
} int_array;
int get(const int_array* self, int x) {
if (x >= self->capacity) return -1;
return *(self->data + x);
}
int set(const int_array* self, int index, int value) {
if (index >= self->capacity) return 0;
*(self->data + index) = value;
return 1;
}
void resize(int_array* self, int size) {
realloc(self->data, size * sizeof(int));
self->capacity = size;
}
void dispose(int_array* self) {
if (self->data == NULL) {
printf("Free a null pointer!");
return;
}
free(self->data);
self->capacity = 0;
self->data = NULL;
}
void print(const int_array* self) {
printf("Array Info: %p\n", self);
printf("Capacity: %d\n", self->capacity);
printf("Data:\n");
for (int i = 0; i < self->capacity; ++i) {
printf("[%d] -> %d\n", i, *(self->data + i));
}
}
int_array new(int cap) {
int* _arr = (int*)calloc(cap, sizeof(int));
printf("_arr: %p", _arr);
struct int_array arr = { cap, _arr };
return arr;
}
int main(void) {
int_array arr = new(12);
print(&arr);
int v = set(&arr, 1, 12);
print(&arr);
printf("Def [1] -> %d\n", get(&arr, 1));
resize(&arr, 3);
print(&arr);
dispose(&arr);
print(&arr);
}