Kodewick
Commencer à apprendre →
Projet : un carnet d’adresses30 / 30

Projet : un carnet d’adresses

Leçon 30 sur 30 · Partie 6 · Pour aller plus loin · environ 20 minutes

Cette leçon construit un carnet d’adresses de zéro, qui ajoute, liste et retrouve des contacts, avec des structures, un tableau qui grandit (realloc) et des fonctions.

Il est temps d’assembler les morceaux. Dans cette leçon, tu vas construire un petit carnet d’adresses, étape par étape. Chaque étape est un programme complet que tu peux lancer, et chacune ajoute un peu à la précédente. Voici le plan :

ÉlémentCe qu’il faitVient de la leçon
Contactune personne : un nom et un numéro de téléphone23, 25
Booktous les contacts, dans un tableau qui grandit22, 24
book_addajoute un contact, en faisant de la place quand c’est plein20, 22
book_listaffiche tout le monde17, 24
book_findcherche un contact par son nom14
book_removeretire un contact11, 23
book_freerend la mémoire20, 21
Choisis-en une

Dans ce carnet d’adresses, quelle fonction rend la mémoire ?

Un contact

Commence par la forme d’un contact : un nom et un numéro de téléphone, deux chaînes. Un numéro est gardé sous forme de texte, pas d’int : il peut commencer par 0 et contient un -.

main.c
1#include <stdio.h>2 3typedef struct {4    char name[20];5    char phone[16];6} Contact;7 8void print_contact(const Contact *c) {9    printf("%s: %s\n", c->name, c->phone);10}11 12int main(void) {13    Contact friends[2] = {14        {"Ana", "555-0101"},15        {"Ben", "555-0102"}16    };17    for (int i = 0; i < 2; i++) {18        print_contact(&friends[i]);19    }20    return 0;21}
Sortie
Ana: 555-0101
Ben: 555-0102

print_contact prend un pointeur, donc la structure n’est pas copiée, et const promet que la fonction se contente de la lire. Un nom doit tenir en 19 caractères, plus le '\0'.

Choisis-en une

Pourquoi le numéro de téléphone est-il rangé dans une chaîne et pas dans un int ?

Un carnet qui grandit

Un tableau fixe de 2 est trop petit, et on ne peut pas savoir à l’avance combien d’amis quelqu’un a. Le carnet garde donc ses contacts sur le tas, dans un tableau qui double de taille quand il est plein, exactement comme la liste qui grandit de la leçon 22. count indique combien de contacts il y a ; capacity, combien peuvent tenir.

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35void book_free(Book *book) {36    free(book->items);37    book->items = NULL;38    book->count = 0;39    book->capacity = 0;40}41 42int main(void) {43    Book book = {NULL, 0, 0};44    book_add(&book, "Ana", "555-0101");45    book_add(&book, "Ben", "555-0102");46    book_add(&book, "Chloe", "555-0103");47    printf("%d contacts, place pour %d\n", book.count, book.capacity);48    book_free(&book);49    return 0;50}
Sortie
3 contacts, place pour 4

Le carnet démarre vide : items vaut NULL et il n’y a aucune place. realloc(NULL, size) fonctionne exactement comme malloc(size), donc le premier book_add obtient de la place pour 2. Le troisième trouve le carnet plein et demande à realloc de la place pour 4. Si realloc échoue, l’ancien bloc est toujours là, et book_add renvoie 0.

Appuie sur Étapes et regarde le tas. Un bloc pour 2 contacts apparaît, puis un bloc pour 4 le remplace, avec Ana et Ben recopiés, et la flèche de book.items s’y déplace. À la fin, book_free rend aussi ce bloc : tous les blocs du tas sont gris, avec la mention « libéré », et aucun n’affiche « fuite ».

pile

book.itemsContact *NULL
book.countint0
book.capacityint0

tas

Ana BenContact[2]
Ana Ben Chloe _Contact[4]

Quand c’est plein, on passe à un bloc plus grand : de la place pour 2 devient de la place pour 4, les contacts déménagent, et à la fin tout le bloc est rendu
Choisis-en uneSe tromper n’est pas grave

Après 5 contacts, combien de places a le carnet ?

1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35int main(void) {36    Book book = {NULL, 0, 0};37    book_add(&book, "Ana", "555-0101");38    book_add(&book, "Ben", "555-0102");39    book_add(&book, "Chloe", "555-0103");40    book_add(&book, "Dan", "555-0104");41    book_add(&book, "Eva", "555-0105");42    printf("place pour %d\n", book.capacity);43    free(book.items);44    return 0;45}

Afficher tout le monde

Pour afficher le carnet, parcours items de 0 à count - 1. Arrête-toi à count, pas à capacity : les cases après count ne contiennent encore rien.

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35void book_list(const Book *book) {36    if (book->count == 0) {37        printf("(vide)\n");38    }39    for (int i = 0; i < book->count; i++) {40        printf("%d. %s: %s\n", i + 1, book->items[i].name, book->items[i].phone);41    }42}43 44void book_free(Book *book) {45    free(book->items);46    book->items = NULL;47    book->count = 0;48    book->capacity = 0;49}50 51int main(void) {52    Book book = {NULL, 0, 0};53    book_list(&book);54    book_add(&book, "Ana", "555-0101");55    book_add(&book, "Ben", "555-0102");56    book_add(&book, "Chloe", "555-0103");57    book_list(&book);58    book_free(&book);59    return 0;60}
Sortie
(vide)
1. Ana: 555-0101
2. Ben: 555-0102
3. Chloe: 555-0103

book_list ne fait que lire le carnet, donc elle prend un const Book *. book_add et book_free le modifient, donc elles prennent un simple Book *.

Choisis-en une

Pourquoi la boucle de book_list s’arrête-t-elle à count et pas à capacity ?

Exercice 1

Enregistrer dans un fichier

Écris book_save : écris chaque contact dans le fichier sur une ligne, le nom, une espace, puis le téléphone, comme Ana 555-0101. Renvoie 0 si le fichier ne peut pas être ouvert, 1 sinon. main relit déjà le fichier et l’affiche.

Il devrait afficher
Ana 555-0101
Ben 555-0102
Chloe 555-0103
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35int book_save(const Book *book, const char *filename) {36 37}38 39int main(void) {40    Book book = {NULL, 0, 0};41    book_add(&book, "Ana", "555-0101");42    book_add(&book, "Ben", "555-0102");43    book_add(&book, "Chloe", "555-0103");44    book_save(&book, "contacts.txt");45    free(book.items);46 47    char line[100];48    FILE *f = fopen("contacts.txt", "r");49    if (f == NULL) {50        printf("Rien d'enregistré\n");51        return 1;52    }53    while (fgets(line, sizeof line, f) != NULL) {54        printf("%s", line);55    }56    fclose(f);57    return 0;58}
Sortie
Appuie sur Exécuter ou Ctrl+Entrée

Chercher par nom

book_find compare chaque nom avec strcmp (== ne fonctionne pas sur les chaînes, leçon 14). Elle renvoie l’indice du contact, ou -1 si personne ne porte ce nom :

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35int book_find(const Book *book, const char *name) {36    for (int i = 0; i < book->count; i++) {37        if (strcmp(book->items[i].name, name) == 0) {38            return i;39        }40    }41    return -1;42}43 44void book_free(Book *book) {45    free(book->items);46    book->items = NULL;47    book->count = 0;48    book->capacity = 0;49}50 51int main(void) {52    Book book = {NULL, 0, 0};53    book_add(&book, "Ana", "555-0101");54    book_add(&book, "Ben", "555-0102");55    book_add(&book, "Chloe", "555-0103");56    const char *wanted[2] = {"Ben", "Zoe"};57    for (int k = 0; k < 2; k++) {58        int i = book_find(&book, wanted[k]);59        if (i == -1) {60            printf("%s: introuvable\n", wanted[k]);61        } else {62            printf("%s: %s\n", wanted[k], book.items[i].phone);63        }64    }65    book_free(&book);66    return 0;67}
Sortie
Ben: 555-0102
Zoe: introuvable

wanted est un tableau de deux pointeurs const char *, chacun pointant vers un nom à chercher. Pourquoi renvoyer un indice plutôt que le numéro de téléphone ? Parce que les autres fonctions peuvent s’en servir aussi : book_remove a besoin de savoir où se trouve le contact.

Choisis-en une

Que renvoie book_find quand le nom n’y est pas ?

Exercice 2

Changer un numéro

Écris book_set_phone : trouve le contact portant ce nom et donne-lui le nouveau numéro. Renvoie 1 si ça a marché et 0 si ce nom n’existe pas. Le programme doit ensuite afficher Ben avec 555-9999.

Il devrait afficher
Pas de Zoe
1. Ana: 555-0101
2. Ben: 555-9999
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35void book_list(const Book *book) {36    for (int i = 0; i < book->count; i++) {37        printf("%d. %s: %s\n", i + 1, book->items[i].name, book->items[i].phone);38    }39}40 41int book_find(const Book *book, const char *name) {42    for (int i = 0; i < book->count; i++) {43        if (strcmp(book->items[i].name, name) == 0) {44            return i;45        }46    }47    return -1;48}49 50int book_set_phone(Book *book, const char *name, const char *phone) {51 52}53 54int main(void) {55    Book book = {NULL, 0, 0};56    book_add(&book, "Ana", "555-0101");57    book_add(&book, "Ben", "555-0102");58    book_set_phone(&book, "Ben", "555-9999");59    if (!book_set_phone(&book, "Zoe", "555-0000")) {60        printf("Pas de Zoe\n");61    }62    book_list(&book);63    free(book.items);64    return 0;65}
Sortie
Appuie sur Exécuter ou Ctrl+Entrée

Supprimer un contact

Pour retirer le contact d’indice i, décale d’une case vers la gauche chaque contact qui le suit, puis diminue count de 1. Affecter une structure à une autre la copie entièrement (leçon 23), nom et téléphone ensemble. L’ordre des autres contacts ne change pas.

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_add(Book *book, const char *name, const char *phone) {17    if (book->count == book->capacity) {18        int new_capacity = book->capacity * 2;19        if (new_capacity == 0) {20            new_capacity = 2;21        }22        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));23        if (bigger == NULL) {24            return 0;25        }26        book->items = bigger;27        book->capacity = new_capacity;28    }29    strcpy(book->items[book->count].name, name);30    strcpy(book->items[book->count].phone, phone);31    book->count++;32    return 1;33}34 35void book_list(const Book *book) {36    if (book->count == 0) {37        printf("(vide)\n");38    }39    for (int i = 0; i < book->count; i++) {40        printf("%d. %s: %s\n", i + 1, book->items[i].name, book->items[i].phone);41    }42}43 44int book_find(const Book *book, const char *name) {45    for (int i = 0; i < book->count; i++) {46        if (strcmp(book->items[i].name, name) == 0) {47            return i;48        }49    }50    return -1;51}52 53int book_remove(Book *book, const char *name) {54    int i = book_find(book, name);55    if (i == -1) {56        return 0;57    }58    for (int j = i; j < book->count - 1; j++) {59        book->items[j] = book->items[j + 1];60    }61    book->count--;62    return 1;63}64 65void book_free(Book *book) {66    free(book->items);67    book->items = NULL;68    book->count = 0;69    book->capacity = 0;70}71 72int main(void) {73    Book book = {NULL, 0, 0};74    book_add(&book, "Ana", "555-0101");75    book_add(&book, "Ben", "555-0102");76    book_add(&book, "Chloe", "555-0103");77    book_add(&book, "Dan", "555-0104");78    book_remove(&book, "Ben");79    if (!book_remove(&book, "Zoe")) {80        printf("Pas de Zoe à supprimer\n");81    }82    book_list(&book);83    printf("%d contacts, place pour %d\n", book.count, book.capacity);84    book_free(&book);85    return 0;86}
Sortie
Pas de Zoe à supprimer
1. Ana: 555-0101
2. Chloe: 555-0103
3. Dan: 555-0104
3 contacts, place pour 4

La boucle s’arrête à count - 1, car items[j + 1] doit encore être un vrai contact. Après la suppression de Ben, il y a de la place pour 4 mais seulement 3 contacts : le carnet ne rétrécit pas, et ce n’est pas grave. Voilà le carnet d’adresses complet. Appuie encore une fois sur Étapes et regarde Chloe prendre la place de Ben, puis Dan celle de Chloe.

itemsAnaBenChloeDan0123

Supprimer le deuxième contact : tous ceux d’après reculent d’une place vers la gauche, puis count baisse de 1
Exercice 3

Pas de doublons

Pour l’instant, tu peux ajouter Ana deux fois. Modifie book_add pour que, si le nom est déjà dans le carnet, elle n’ajoute rien et renvoie 0. Le programme doit afficher Ana est déjà là et ne lister que 2 contacts.

Il devrait afficher
Ana est déjà là
1. Ana: 555-0101
2. Ben: 555-0102
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5typedef struct {6    char name[20];7    char phone[16];8} Contact;9 10typedef struct {11    Contact *items;12    int count;13    int capacity;14} Book;15 16int book_find(const Book *book, const char *name) {17    for (int i = 0; i < book->count; i++) {18        if (strcmp(book->items[i].name, name) == 0) {19            return i;20        }21    }22    return -1;23}24 25int book_add(Book *book, const char *name, const char *phone) {26    if (book->count == book->capacity) {27        int new_capacity = book->capacity * 2;28        if (new_capacity == 0) {29            new_capacity = 2;30        }31        Contact *bigger = realloc(book->items, new_capacity * sizeof(Contact));32        if (bigger == NULL) {33            return 0;34        }35        book->items = bigger;36        book->capacity = new_capacity;37    }38    strcpy(book->items[book->count].name, name);39    strcpy(book->items[book->count].phone, phone);40    book->count++;41    return 1;42}43 44void book_list(const Book *book) {45    for (int i = 0; i < book->count; i++) {46        printf("%d. %s: %s\n", i + 1, book->items[i].name, book->items[i].phone);47    }48}49 50int main(void) {51    Book book = {NULL, 0, 0};52    book_add(&book, "Ana", "555-0101");53    book_add(&book, "Ben", "555-0102");54    if (!book_add(&book, "Ana", "555-0199")) {55        printf("Ana est déjà là\n");56    }57    book_list(&book);58    free(book.items);59    return 0;60}
Sortie
Appuie sur Exécuter ou Ctrl+Entrée

Tout libérer

Chaque bloc obtenu avec malloc ou realloc a besoin d’exactement un free. Le carnet n’a qu’un seul bloc, items, car les contacts sont dedans : book_free n’a donc besoin que d’un free. Elle met ensuite items à NULL et les compteurs à 0, pour que le carnet soit de nouveau un carnet vide valide : tu pourrais rappeler book_add dessus, ou appeler book_free deux fois sans libérer deux fois le même bloc.

Oublie book_free, et le bloc reste occupé jusqu’à la fin du programme. C’est la fuite de mémoire de la leçon 21. Dans un programme qui tourne longtemps, comme l’application de contacts d’un téléphone, les fuites s’accumulent.

Astuce : Écris la fonction qui libère quelque chose en même temps que celle qui le crée. Ainsi, chaque book_add a son book_free dès le départ.

Choisis-en une

Après book_free(&book);, tu appelles encore book_free(&book); par erreur. Que se passe-t-il ?

Ce que tu as appris

  • Un programme plus gros se construit avec de petites fonctions qui font chacune un seul travail : ajouter, lister, chercher, supprimer, libérer.
  • Une structure contient un enregistrement ; une deuxième structure contient le tableau, son count et sa capacity.
  • Le tableau vit sur le tas et double de taille avec realloc quand il est plein ; realloc(NULL, size) équivaut à malloc(size).
  • Les fonctions qui ne font que lire prennent un pointeur const ; celles qui modifient le carnet prennent un simple pointeur.
  • Retirer un élément au milieu oblige à décaler les suivants d’une case vers la gauche.
  • Chaque bloc obtenu reçoit un seul free ; après la libération, mets le pointeur à NULL.
Tu as terminé cette leçon ?Marque-la. Ta progression est gardée dans ce navigateur, et tu peux annuler.