Projekt: ein Adressbuch
In dieser Lektion baust du von Grund auf ein Adressbuch, das Kontakte hinzufügt, auflistet und findet, mit Strukturen, einem wachsenden Array (realloc) und Funktionen.
Zeit, die Teile zusammenzusetzen. In dieser Lektion baust du Schritt für Schritt ein kleines Adressbuch. Jeder Schritt ist ein vollständiges Programm, das du ausführen kannst, und jeder fügt dem vorherigen ein bisschen hinzu. Das ist der Plan:
| Teil | Was es tut | Aus Lektion |
|---|---|---|
Contact | eine Person: ein Name und eine Telefonnummer | 23, 25 |
Book | alle Kontakte, in einem Array, das wächst | 22, 24 |
book_add | fügt einen Kontakt hinzu und schafft Platz, wenn es voll ist | 20, 22 |
book_list | zeigt alle an | 17, 24 |
book_find | sucht einen Kontakt nach Namen | 14 |
book_remove | nimmt einen Kontakt heraus | 11, 23 |
book_free | gibt den Speicher zurück | 20, 21 |
Welche Funktion dieses Adressbuchs gibt den Speicher zurück?
book_remove nimmt nur einen Kontakt aus dem Array; der Speicher bleibt belegt. Den Block, den realloc geliefert hat, gibt book_free zurück.Ein Kontakt
Fang damit an, wie ein Kontakt aussieht: ein Name und eine Telefonnummer, beides Strings. Eine Telefonnummer speichert man als Text, nicht als int: Sie kann mit 0 beginnen und enthält ein -.
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}
Ana: 555-0101 Ben: 555-0102
print_contact bekommt einen Zeiger, damit die Struktur nicht kopiert wird, und const verspricht, dass die Funktion sie nur liest. Ein Name muss in 19 Zeichen passen, plus das '\0'.
Warum wird die Telefonnummer als String gespeichert und nicht als int?
int würde die führende 0 verlieren und hat keinen Platz für ein -. Mit Telefonnummern rechnet man nie, also passt Text am besten.Ein Buch, das wächst
Ein festes Array mit 2 Plätzen ist zu klein, und wie viele Freunde jemand hat, weißt du vorher nicht. Deshalb hält das Buch seine Kontakte auf dem Heap, in einem Array, das sich verdoppelt, wenn es voll ist, genau wie die wachsende Liste in Lektion 22. count ist die Anzahl der Kontakte; capacity ist, wie viele hineinpassen.
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 Kontakte, Platz für %d\n", book.count, book.capacity);48 book_free(&book);49 return 0;50}
3 Kontakte, Platz für 4
Das Buch beginnt leer: items ist NULL, und es gibt überhaupt keinen Platz. realloc(NULL, size) funktioniert genau wie malloc(size), also bekommt das erste book_add Platz für 2. Das dritte findet das Buch voll vor und bittet realloc um Platz für 4. Scheitert realloc, ist der alte Block noch da, und book_add gibt 0 zurück.
Drück auf Schritte und beobachte den Heap. Ein Block für 2 Kontakte erscheint, dann wird er durch einen Block für 4 ersetzt, in den Ana und Ben kopiert werden, und der Pfeil von book.items springt dorthin. Am Ende gibt book_free auch diesen Block zurück: Jeder Block auf dem Heap ist grau und „freigegeben“, und keiner ist als „Speicherleck“ markiert.
Stack
book.itemsContact *NULLbook.countint0book.capacityint0Heap
Wie viele Kontakte passen nach 5 Kontakten ins Buch?
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("Platz für %d\n", book.capacity);43 free(book.items);44 return 0;45}
Alle auflisten
Um das Buch anzuzeigen, geh items von 0 bis count - 1 durch. Hör bei count auf, nicht bei capacity: In die Plätze nach count wurde noch nichts geschrieben.
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("(leer)\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}
(leer) 1. Ana: 555-0101 2. Ben: 555-0102 3. Chloe: 555-0103
book_list liest das Buch nur, also bekommt es ein const Book *. book_add und book_free ändern es, also bekommen sie ein einfaches Book *.
Warum läuft die Schleife in book_list nur bis count und nicht bis capacity?
capacity sagt, wie viele hineinpassen, count, wie viele da sind. Auf die Plätze nach count wurde noch nichts geschrieben, also kann man sie nicht als Kontakte anzeigen.In einer Datei speichern
✓Schreib book_save: Schreib jeden Kontakt als eine Zeile in die Datei, den Namen, ein Leerzeichen, dann die Telefonnummer, etwa Ana 555-0101. Gib 0 zurück, wenn sich die Datei nicht öffnen lässt, sonst 1. main liest die Datei schon zurück und gibt sie aus.
Ana 555-0101 Ben 555-0102 Chloe 555-0103
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("Nichts gespeichert\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}
Nach Namen suchen
book_find vergleicht jeden Namen mit strcmp (== funktioniert bei Strings nicht, Lektion 14). Es gibt den Index des Kontakts zurück, oder -1, wenn niemand diesen Namen hat:
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: nicht gefunden\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}
Ben: 555-0102 Zoe: nicht gefunden
wanted ist ein Array aus zwei const char *-Zeigern, die jeweils auf einen gesuchten Namen zeigen. Warum gibt die Funktion einen Index zurück statt der Telefonnummer? Weil die anderen Funktionen ihn auch nutzen können: book_remove muss wissen, wo der Kontakt steht.
Was gibt book_find zurück, wenn der Name nicht vorkommt?
0 sein (der erste Kontakt). Für „nicht gefunden“ braucht es also eine Zahl, die nie ein Index sein kann: -1.Eine Nummer ändern
✓Schreib book_set_phone: Such den Kontakt mit diesem Namen und gib ihm die neue Telefonnummer. Gib 1 zurück, wenn es geklappt hat, und 0, wenn es den Namen nicht gibt. Danach soll das Programm Ben mit 555-9999 auflisten.
Keine Zoe 1. Ana: 555-0101 2. Ben: 555-9999
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("Keine Zoe\n");61 }62 book_list(&book);63 free(book.items);64 return 0;65}
Einen Kontakt entfernen
Um den Kontakt mit Index i herauszunehmen, rückst du jeden Kontakt dahinter um eine Stelle nach links und machst count um eins kleiner. Eine Struktur einer anderen zuzuweisen kopiert sie ganz (Lektion 23), Name und Telefonnummer zusammen. Die Reihenfolge der anderen bleibt gleich.
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("(leer)\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("Keine Zoe zum Entfernen\n");81 }82 book_list(&book);83 printf("%d Kontakte, Platz für %d\n", book.count, book.capacity);84 book_free(&book);85 return 0;86}
Keine Zoe zum Entfernen 1. Ana: 555-0101 2. Chloe: 555-0103 3. Dan: 555-0104 3 Kontakte, Platz für 4
Die Schleife hört bei count - 1 auf, weil items[j + 1] noch ein echter Kontakt sein muss. Nach dem Entfernen von Ben ist Platz für 4, aber es gibt nur 3 Kontakte: Das Buch wird nicht kleiner, und das ist in Ordnung. Das ist das ganze Adressbuch. Drück noch einmal auf Schritte und verfolge, wie Chloe den Platz von Ben einnimmt und dann Dan den von Chloe.
Keine Doppelten
✓Im Moment kannst du Ana zweimal hinzufügen. Ändere book_add so, dass es nichts hinzufügt und 0 zurückgibt, wenn der Name schon im Buch steht. Das Programm soll Ana steht schon drin ausgeben und nur 2 Kontakte auflisten.
Ana steht schon drin 1. Ana: 555-0101 2. Ben: 555-0102
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 steht schon drin\n");56 }57 book_list(&book);58 free(book.items);59 return 0;60}
Alles freigeben
Jeder Block von malloc oder realloc braucht genau ein free. Das Buch hat nur einen Block, items, weil die Kontakte darin liegen, also braucht book_free nur ein free. Danach setzt es items auf NULL und die Zähler auf 0, damit das Buch wieder ein gültiges leeres Buch ist: Du könntest noch einmal book_add darauf aufrufen oder book_free zweimal aufrufen, ohne denselben Block zweimal freizugeben.
Vergisst du book_free, bleibt der Block belegt, bis das Programm endet. Das ist das Speicherleck aus Lektion 21. In einem Programm, das lange läuft, etwa der Kontakte-App eines Handys, häufen sich solche Lecks an.
Tipp: Schreib die Funktion, die etwas freigibt, gleichzeitig mit der, die es anlegt. Dann hat jedes book_add von Anfang an ein passendes book_free.
Nach book_free(&book); rufst du aus Versehen noch einmal book_free(&book); auf. Was passiert?
book_free setzt items nach dem Freigeben auf NULL. Der zweite Aufruf macht free(NULL), und das tut laut Regel nichts. Ohne dieses NULL würde der zweite Aufruf denselben Block zweimal freigeben, und die Engine hielte in dieser Zeile an.Das hast du gelernt
- Ein größeres Programm besteht aus kleinen Funktionen, die jeweils eine Aufgabe erledigen: hinzufügen, auflisten, suchen, entfernen, freigeben.
- Eine Struktur hält einen Datensatz; eine zweite Struktur hält das Array, seinen Zähler
countund seine Kapazitätcapacity. - Das Array liegt auf dem Heap und verdoppelt sich mit
realloc, wenn es voll ist;realloc(NULL, size)ist wiemalloc(size). - Funktionen, die nur lesen, bekommen einen
const-Zeiger; Funktionen, die das Buch ändern, einen einfachen Zeiger. - Aus der Mitte entfernen heißt, die späteren Einträge um eine Stelle nach links zu rücken.
- Jeder Block, den du bekommst, bekommt ein
free; setz den Zeiger nach dem Freigeben aufNULL.