This commit is contained in:
2026-03-02 02:12:28 +01:00
parent 88b0c96605
commit 77cd47526c
7 changed files with 572 additions and 0 deletions
+113
View File
@@ -0,0 +1,113 @@
#include "village.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int add_villager(struct villager **village, unsigned int *population, struct villager villager){
if(!village || population == 0) return -1;
struct villager *tmp = realloc(*village, (*population + 1) * sizeof(struct villager));
if(!tmp) return -2;
*village = tmp;
(*village)[*population] = villager;
(*population) ++;
return 0;
}
int remove_villager(struct villager **village, unsigned int *population, char *name){
if(!village || population == 0 || !name) return -1;
if(*population == 1){
if(!strcmp(village[0]->name, name)){
free(*village);
*village = NULL;
*population = 0;
}
return 0;
}
size_t index = 0;
int found = 0;
while(index < *population){
if(found != 0){
(*village)[index - 1] = (*village)[index];
}
if(!strcmp((*village)[index].name, name)) found ++;
index ++;
}
*population -= found;
if(*population > 0) *village = realloc(*village, (*population) * sizeof(struct villager));
else {
free(*village);
*village = NULL;
}
return 0;
}
void clear_village(struct villager **village, unsigned int *population){
if(!village || population == 0) return ;
/*for(size_t i = 0; i < *population; i ++){
free(village[i]);
village[i] = NULL;
}
//free(village);
*/
for (unsigned int i = 0; i < *population; i++){
village[i] = NULL;
}
*population = 0;
}
/*
int main(void)
{
struct villager *village = NULL;
unsigned int population = 0;
struct villager tom_nook = {
.name = "Tom Nook",
.age = 99,
.job = SELLER,
.favorite_quote = "It's 42 bells",
};
add_villager(&village, &population, tom_nook);
struct villager marie = {
.name = "Marie",
.age = 23,
.job = WORKER,
.favorite_quote = "It's so expensive!",
};
add_villager(&village, &population, marie);
clear_village(&village, &population);
for (unsigned int i = 0; i < population; i++)
{
printf("I'm %s (%d)\n", village[i].name, village[i].age);
}
printf("%p\n", village);
printf("%u\n", population);
}
*/