Skip to content

Commit 6fcd13d

Browse files
Implement array in c
1 parent c206df9 commit 6fcd13d

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

c-cpp/05_array/array.c

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
struct array {
6+
int size;
7+
int used;
8+
int *arr;
9+
};
10+
11+
void dump(struct array *array)
12+
{
13+
int idx;
14+
15+
for (idx = 0; idx < array->used; idx++)
16+
printf("[%02d]: %08d\n", idx, array->arr[idx]);
17+
}
18+
19+
void alloc(struct array *array)
20+
{
21+
array->arr = (int *)malloc(array->size * sizeof(int));
22+
}
23+
24+
int insert(struct array *array, int elem)
25+
{
26+
int idx;
27+
if (array->used >= array->size)
28+
return -1;
29+
30+
for (idx = 0; idx < array->used; idx++) {
31+
if (array->arr[idx] > elem)
32+
break;
33+
}
34+
35+
if (idx < array->used)
36+
memmove(&array->arr[array->used], &array->arr[idx],
37+
(array->used - idx) * sizeof(int));
38+
39+
array->arr[idx] = elem;
40+
array->used++;
41+
return idx;
42+
}
43+
44+
int delete(struct array *array, int idx)
45+
{
46+
if (idx < 0 || idx >= array->used)
47+
return -1;
48+
49+
memmove(&array->arr[idx], &array->arr[idx+1],
50+
(array->used - idx) * sizeof(int));
51+
array->used--;
52+
return 0;
53+
}
54+
55+
int search(struct array *array, int elem)
56+
{
57+
int idx;
58+
59+
for (idx = 0; idx < array->used; idx++) {
60+
if (array->arr[idx] == elem)
61+
return idx;
62+
if (array->arr[idx] > elem)
63+
return -1;
64+
}
65+
66+
return -1;
67+
}
68+
69+
int main()
70+
{
71+
int idx;
72+
struct array ten_int = {10, 0, NULL};
73+
74+
alloc(&ten_int);
75+
if (!ten_int.arr)
76+
return -1;
77+
insert(&ten_int, 1);
78+
insert(&ten_int, 3);
79+
insert(&ten_int, 2);
80+
printf("=== insert 1, 3, 2\n");
81+
dump(&ten_int);
82+
83+
idx = search(&ten_int, 2);
84+
printf("2 is at position %d\n", idx);
85+
idx = search(&ten_int, 9);
86+
printf("9 is at position %d\n", idx);
87+
88+
printf("=== delete [6] element \n");
89+
delete(&ten_int, 6);
90+
dump(&ten_int);
91+
printf("=== delete [0] element \n");
92+
delete(&ten_int, 0);
93+
dump(&ten_int);
94+
return 0;
95+
}

0 commit comments

Comments
 (0)