This repository has been archived on 2026-05-11. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
prog-103-p-04-2030/HolidayTrip/Proficiencies/animals/vector.c
T
2026-02-13 16:12:39 +01:00

73 lines
1.8 KiB
C

#include <stddef.h>
#include <stdlib.h>
#include "vector.h"
#include <stdio.h>
#include <strings.h>
#include "animals.h"
struct vector *vector_init(size_t n){
//if (n < 0) return NULL;
struct vector *vector = malloc(sizeof(struct vector));
vector->animal = malloc((n) * sizeof(struct animal));
if(vector->animal == NULL) return NULL;
vector->capacity = n;
vector->size = 0;
return vector;
}
struct vector *vector_resize(struct vector *v, size_t new_capacity){
if(v == NULL) return NULL;
v->animal = realloc(v->animal, (new_capacity + 1) * sizeof(struct animal));
v->capacity = new_capacity;
return v;
}
struct vector *vector_append(struct vector *v, struct animal *animal){
if(v == NULL || animal == NULL) return NULL;
if (v->capacity <= v->size) v = vector_resize(v, v->capacity * 2);
// TODO A voir si le realloc ajoute de l'espace a gauche ou a droite
// car sinon y a ecrasement de data
*(v->animal + (v->capacity - v->size )) = animal;
v->size ++;
return v;
}
void free_animal(struct animal *animal){
if (animal == NULL) return;
//if(animal->color != NULL) free(animal->color);
printf("%s\n",animal->animal.fish->species);
printf("%s\n", animal->animal.insect->species);
if(animal->type == INSECT) free_insect(animal->animal.insect);
if(animal->type == FISH) free_fish(animal->animal.fish);
free(animal->color);
free(animal);
}
void vector_destroy(struct vector *v){
if(v == NULL) return;
if(v->animal != NULL){
//size_t index = 1;
/*while (index < (v->capacity - v->size)){
free_animal(*(v->animal + (v->size - index)));
}*/
for(size_t i = 0; i < v->size; i++) free_animal(v->animal[i]);
}
free(v->animal);
free(v);
//free_animal(v->animal);
}