TP 13 exo1: return the dynamic array created or modified when necessary
[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(int) * tab_size);
7 if (tab == NULL) {
8 return NULL;
9 } else {
10 /* initialize to zero the integer array */
11 for (unsigned i = 0; i < tab_size; i++) {
12 tab[i] = 0;
13 }
14 return tab;
15 }
16 }
17
18 void free_tab(int tab[]) {
19 free(tab);
20 }
21
22 /* we suppose both tabs are already created */
23 static void copy_tab(int src_tab[], int dest_tab[], unsigned src_tab_size, unsigned index_offset) {
24 /* FIXME: I think it's worth doing some sanity checks on the array size:
25 * dest_tab_size >= src_tab_size */
26 for (unsigned i = 0; i < src_tab_size; i++) {
27 dest_tab[i + index_offset] = src_tab[i];
28 }
29 }
30
31 int* concat_tab(int tab1[], unsigned tab_size1, int tab2[], unsigned tab_size2, int tab_dest[]) {
32 int* rt = create_tab(tab_dest, tab_size1 + tab_size2);
33
34 copy_tab(tab1, tab_dest, tab_size1, 0);
35 copy_tab(tab2, tab_dest, tab_size2, tab_size1);
36 return rt;
37 }
38
39 int* resize_tab(int tab[], unsigned new_tab_size) {
40 tab = realloc(tab, sizeof(int) * new_tab_size);
41 if (tab == NULL) {
42 return NULL;
43 } else {
44 return tab;
45 }
46 }
47
48 /* number of occurences of an element in an unsorted array */
49 int count_tab_element(int tab[], unsigned tab_size, int element) {
50 unsigned el_count = 0;
51 for (unsigned i = 0; i < tab_size; i++) {
52 if (tab[i] == element) {
53 el_count++;
54 }
55 }
56 return el_count;
57 }
58
59 void sort_tab(int tab[], unsigned tab_size, criteria_cb criteria) {
60 sort_bubble_array(tab, tab_size, criteria);
61 }