- Zusammenfassung von zusammengehörigen Daten in eigenen Datentyp durch struct
- Beispiel Produkte mit Namen und Preis:
struct produkt { // Definition
char name[255];
float preis;
};
struct produkt beispiel; // Deklaration
- Zugriff durch Selektor
. (Punkt)
beispiel.preis = 0.79;
strncpy(beispiel.name, "Apfel", 255);
printf("Ware %s mit Preis %f\n",
beispiel.name, beispiel.preis);
- Beispiel Produkte mit Namen und Preis mit Pointer
struct produkt {
char name[255];
float preis;
};
struct produkt beispiel;
struct produkt warenkorb[100];
struct produkt *ware = warenkorb;
- Zugriff bei Pointern durch slektor
-> ("Pfeil")
printf("Produkt %s mit Preis %f\n",
ware->name, ware->preis);
```
- Typdefinition
- oft sinnvoll, eigene Typen zu definiere mittels `typedef`
- Beispiel
```c
typedef struct produkt {
char name[255];
float preis;
} produkt_t;
// Variablendeklaration
produkt_t produkt1, produkt2;
```
- Warum? Bessere Lesbarkeit, bessere Dokumentation