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