CodeBlanks Logo Icon CodeBlanks

Summary - Advanced structs

  • C course
  • Intermediate
  • Lesson 35/116
  • 5 min

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.

Practice 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);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>

// Define struct Person (name[32] and age)
// Allocate a 3-element struct Person array with malloc
// Assign each age with for, print, then call free

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

30
25
35

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.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 To access age via struct Person *p?

  • p->age Correct answer
  • *p.age
  • p.age
  • &p.age

Explanation: The -> operator is used for pointers.

2 Match concepts to syntax

Term Meaning
p->age Pointer access
people[0].age Array element access
e.when.day Nested access
malloc(sizeof(...)) Dynamic allocation

All lessons in Intermediate