TP 13 exo1: create an array in the main()
[TD_C.git] / TP_13 / exo1 / lib / array.c
1 #include <stdlib.h>
2
3 #include "array.h"
4
5 int create_tab(int tab[], unsigned tab_size) {
6 tab = malloc(sizeof(unsigned) * tab_size);
7 if (tab == NULL) {
8 return -1;
9 } else {
10 return 0;
11 }
12 }
13
14 void free_tab(int tab[]) {
15 free(tab);
16 }
17
18 /* we suppose both tab are already created */
19 static void copy_tab(int src_tab[], int dest_tab[], unsigned min_tab_size, unsigned index_offset) {
20 /* FIXME: I think it's worth doing some sanity check on the array size */
21 for (unsigned i = 0; i < min_tab_size; i++) {
22 dest_tab[i + index_offset] = src_tab[i];
23 }
24 }
25
26 int concat_tab(int tab1[], unsigned tab_size1, int tab2[], unsigned tab_size2, int tab_dest[]) {
27 int rt = create_tab(tab_dest, tab_size1 + tab_size2);
28
29 copy_tab(tab1, tab_dest, tab_size1, 0);
30 copy_tab(tab2, tab_dest, tab_size2, tab_size1);
31 return rt;
32 }
33
34 int resize_tab(int tab[], unsigned tab_size) {
35 tab = realloc(tab, sizeof(int) * tab_size);
36 if (tab == NULL) {
37 return -1;
38 } else {
39 return 0;
40 }
41 }
42
43 /* number of occurences of an element in an unsorted array */
44 int count_tab_element(int tab[], unsigned tab_size, int element) {
45 unsigned el_count = 0;
46 for (unsigned i = 0; i < tab_size; i++) {
47 if (tab[i] == element) {
48 el_count++;
49 }
50 }
51 return el_count;
52 }
53
54 void sort_tab(int tab[], unsigned tab_size, criteria_cb criteria) {
55 sort_bubble_array(tab, tab_size, criteria);
56 }