C
Summary - Advanced structs
Combine struct pointer, dynamic struct and array to write a person database.
Summary - Advanced structs
In this summary you'll combine advanced struct concepts to write a person database. Throughout the group you learned the struct pointer, dynamic struct, pointer-parameter function, nested struct and struct array.
The database uses these parts: the struct Person definition, a 3-element array with malloc, access with a for loop, and printing each element's age field. In a real app these parts become add, search and sort functions. C databases, game records and configuration systems start with this pattern.
Exercise Write a person database
Define struct Person with char name[32]; and int age;. In main, allocate a dynamic array with struct Person *people = malloc(3 * sizeof(struct Person));. Check with if (people == NULL) return 1;. Assign people[0].age = 30;, people[1].age = 25;, people[2].age = 35;. With a for loop, print each age with printf("%d\n", people[i].age);. Finally call free(people);.
Show example solution
#include <stdio.h>
#include <stdlib.h>
struct Person {
char name[32];
int age;
};
int main(void) {
struct Person *people = malloc(3 * sizeof(struct Person));
if (people == NULL) return 1;
people[0].age = 30;
people[1].age = 25;
people[2].age = 35;
for (int i = 0; i < 3; i++) {
printf("%d\n", people[i].age);
}
free(people);
return 0;
}
Summary
In this group you learned advanced struct concepts: pointer access (->), dynamic struct (malloc), struct functions, nested struct and struct array.
You combined these to write a dynamic person database. These patterns are the foundation of data management in C: operating systems hold record blocks, games hold score tables, databases hold rows this way. In the next groups you'll learn union, enum and bit fields for memory optimization; this will let you pack data structures even tighter.
Test yourself
-
To access age via struct Person *p?
Show answer
p->age — The -> operator is used for pointers.
-
Match concepts to syntax
- p->age
- Pointer access
- people[0].age
- Array element access
- e.when.day
- Nested access
- malloc(sizeof(...))
- Dynamic allocation
Next lesson: union