C: Practice: Custom Types

🗓 Last updated: 2026-11-30👤 Written by: Ivy✓ Reviewed by: Dana🏷 Category: C Tutorial

You've learned enough — now it's time to build something. Like learning to cook: reading recipes isn't enough; you have to get in the kitchen. Combine structs, dynamic memory, and file I/O to create working programs.

Reference entries in this section: realloc free

1. Project 1: Student Grade Management System

(1) Requirements

(2) Data Structure Design

C
// Type definition
typedef struct {
    char name[32];
    char id[16];
    // Variable declaration
    int chinese;
    // Variable declaration
    int math;
    // Variable declaration
    int english;
} Student;

// Type definition
typedef struct {
    Student *data;
    // Variable declaration
    int count;
    // Variable declaration
    int capacity;
} StudentList;

StudentList manages students with a dynamic array — initial capacity is 4, expanding when full.

(3) Core Implementation

C
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Preprocessor directive
#include <string.h>

// Type definition
typedef struct {
    char name[32];
    char id[16];
    // Variable declaration
    int chinese;
    // Variable declaration
    int math;
    // Variable declaration
    int english;
} Student;

// Type definition
typedef struct {
    Student *data;
    // Variable declaration
    int count;
    // Variable declaration
    int capacity;
} StudentList;

// Function definition
void list_init(StudentList *list) {
    list->capacity = 4;
    list->count = 0;
    list->data = (Student *)malloc(sizeof(Student) * list->capacity);
}

// Function definition
void list_free(StudentList *list) {
    // Dynamic memory operation
    free(list->data);
    list->data = NULL;
    list->count = 0;
    list->capacity = 0;
}

// Function definition
void list_expand(StudentList *list) {
    // Conditional check
    if (list->count < list->capacity) return;
    list->capacity *= 2;
    Student *tmp = (Student *)realloc(list->data, sizeof(Student) * list->capacity);
    // Conditional check
    if (tmp) list->data = tmp;
}

// Function definition
void list_add(StudentList *list, const Student *s) {
    list_expand(list);
    list->data[list->count++] = *s;
}

// Function definition
int total_score(const Student *s) {
    // Return result
    return s->chinese + s->math + s->english;
}

// Function definition
double avg_score(const Student *s) {
    // Return result
    return total_score(s) / 3.0;
}

Student *find_by_id(StudentList *list, const char *id) {
    // For loop
    for (int i = 0; i < list->count; i++) {
        // Conditional check
        if (strcmp(list->data[i].id, id) == 0) {
            // Return result
            return &list->data[i];
        }
    }
    // Return result
    return NULL;
}

// Function definition
int cmp_by_total(const void *a, const void *b) {
    // Variable declaration
    int ta = total_score((const Student *)a);
    // Variable declaration
    int tb = total_score((const Student *)b);
    // Return result
    return tb - ta;
}

// Function definition
void sort_by_total(StudentList *list) {
    qsort(list->data, list->count, sizeof(Student), cmp_by_total);
}

// Function definition
void print_student(const Student *s) {
    // I/O operation
    printf("%-6s %-10s Chinese:%-3d Math:%-3d English:%-3d Total:%-4d Avg:%.1f\n",
           s->id, s->name, s->chinese, s->math, s->english,
           total_score(s), avg_score(s));
}

// Function definition
void print_all(const StudentList *list) {
    // I/O operation
    printf("ID     Name        Chinese Math English Total Avg\n");
    // I/O operation
    printf("----------------------------------------------------------\n");
    // For loop
    for (int i = 0; i < list->count; i++) {
        print_student(&list->data[i]);
    }
}

// Function definition
int save_to_file(const StudentList *list, const char *filename) {
    FILE *fp = fopen(filename, "w");
    // Conditional check
    if (!fp) return -1;
    fprintf(fp, "%d\n", list->count);
    // For loop
    for (int i = 0; i < list->count; i++) {
        Student *s = &list->data[i];
        fprintf(fp, "%s %s %d %d %d\n", s->id, s->name,
                s->chinese, s->math, s->english);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}

// Function definition
int load_from_file(StudentList *list, const char *filename) {
    FILE *fp = fopen(filename, "r");
    // Conditional check
    if (!fp) return -1;
    // Variable declaration
    int n;
    fscanf(fp, "%d", &n);
    // For loop
    for (int i = 0; i < n; i++) {
        Student s;
        fscanf(fp, "%s %s %d %d %d", s.id, s.name,
               &s.chinese, &s.math, &s.english);
        list_add(list, &s);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}

▶ Example

TEXT
int main(void) {
    StudentList list;
    list_init(&list);

    Student s1 = {"001", "Alice", 85, 92, 78};
    Student s2 = {"002", "Bob", 90, 88, 95};
    Student s3 = {"003", "Carol", 72, 65, 80};

    list_add(&list, &s1);
    list_add(&list, &s2);
    list_add(&list, &s3);

    printf("--- All Students ---\n");
    print_all(&list);

    sort_by_total(&list);
    printf("\n--- Sorted by Total ---\n");
    print_all(&list);

    Student *found = find_by_id(&list, "001");
    if (found) {
        printf("\nFound 001: %s Total=%d\n", found->name, total_score(found));
    }

    save_to_file(&list, "students.dat");
    printf("\nSaved to students.dat\n");

    list_free(&list);
    return 0;
}
TEXT
--- All Students ---
ID     Name        Chinese Math English Total Avg
----------------------------------------------------------
001    Alice       Chinese:85  Math:92  English:78  Total:255  Avg:85.0
002    Bob          Chinese:90  Math:88  English:95  Total:273  Avg:91.0
003    Carol        Chinese:72  Math:65  English:80  Total:217  Avg:72.3

--- Sorted by Total ---
ID     Name        Chinese Math English Total Avg
----------------------------------------------------------
002    Bob          Chinese:90  Math:88  English:95  Total:273  Avg:91.0
001    Alice       Chinese:85  Math:92  English:78  Total:255  Avg:85.0
003    Carol        Chinese:72  Math:65  English:80  Total:217  Avg:72.3

Found 001: Alice Total=255

Saved to students.dat

2. Project 2: Contact Management

(1) Requirements

(2) Data Structure Design

C
// Type definition
typedef struct {
    char name[32];
    char phone[16];
    char email[40];
    char group[16];
} Contact;

// Type definition
typedef struct {
    Contact *data;
    // Variable declaration
    int count;
    // Variable declaration
    int capacity;
} ContactList;

(3) Core Implementation

C
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Preprocessor directive
#include <string.h>

// Type definition
typedef struct {
    char name[32];
    char phone[16];
    char email[40];
    char group[16];
} Contact;

// Type definition
typedef struct {
    Contact *data;
    // Variable declaration
    int count;
    // Variable declaration
    int capacity;
} ContactList;

// Function definition
void clist_init(ContactList *list) {
    list->capacity = 4;
    list->count = 0;
    list->data = (Contact *)malloc(sizeof(Contact) * list->capacity);
}

// Function definition
void clist_free(ContactList *list) {
    // Dynamic memory operation
    free(list->data);
    list->data = NULL;
    list->count = 0;
    list->capacity = 0;
}

// Function definition
void clist_expand(ContactList *list) {
    // Conditional check
    if (list->count < list->capacity) return;
    list->capacity *= 2;
    Contact *tmp = (Contact *)realloc(list->data, sizeof(Contact) * list->capacity);
    // Conditional check
    if (tmp) list->data = tmp;
}

// Function definition
void clist_add(ContactList *list, const Contact *c) {
    clist_expand(list);
    list->data[list->count++] = *c;
}

// Function definition
int clist_remove(ContactList *list, const char *name) {
    // For loop
    for (int i = 0; i < list->count; i++) {
        // Conditional check
        if (strcmp(list->data[i].name, name) == 0) {
            list->data[i] = list->data[list->count - 1];
            list->count--;
            // Return result
            return 0;
        }
    }
    // Return result
    return -1;
}

Contact *clist_find(ContactList *list, const char *name) {
    // For loop
    for (int i = 0; i < list->count; i++) {
        // Conditional check
        if (strcmp(list->data[i].name, name) == 0) {
            // Return result
            return &list->data[i];
        }
    }
    // Return result
    return NULL;
}

// Function definition
void clist_filter_by_group(const ContactList *list, const char *group) {
    // I/O operation
    printf("--- Group: %s ---\n", group);
    // For loop
    for (int i = 0; i < list->count; i++) {
        // Conditional check
        if (strcmp(list->data[i].group, group) == 0) {
            // I/O operation
            printf("%s  %s  %s\n", list->data[i].name,
                   list->data[i].phone, list->data[i].email);
        }
    }
}

// Function definition
void print_contact(const Contact *c) {
    // I/O operation
    printf("%-8s %-14s %-24s %s\n", c->name, c->phone, c->email, c->group);
}

// Function definition
void print_all_contacts(const ContactList *list) {
    // I/O operation
    printf("%-8s %-14s %-24s %s\n", "Name", "Phone", "Email", "Group");
    // I/O operation
    printf("---------------------------------------------------------\n");
    // For loop
    for (int i = 0; i < list->count; i++) {
        print_contact(&list->data[i]);
    }
}

// Function definition
int save_contacts(const ContactList *list, const char *filename) {
    FILE *fp = fopen(filename, "w");
    // Conditional check
    if (!fp) return -1;
    fprintf(fp, "%d\n", list->count);
    // For loop
    for (int i = 0; i < list->count; i++) {
        Contact *c = &list->data[i];
        fprintf(fp, "%s %s %s %s\n", c->name, c->phone, c->email, c->group);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}

// Function definition
int load_contacts(ContactList *list, const char *filename) {
    FILE *fp = fopen(filename, "r");
    // Conditional check
    if (!fp) return -1;
    // Variable declaration
    int n;
    fscanf(fp, "%d", &n);
    // For loop
    for (int i = 0; i < n; i++) {
        Contact c;
        fscanf(fp, "%s %s %s %s", c.name, c.phone, c.email, c.group);
        clist_add(list, &c);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 0;
}

▶ Example

▶ Try it Yourself
TEXT
--- All Contacts ---
Name     Phone           Email                    Group
---------------------------------------------------------
Alice    13800001111     alice@mail.com        Coworker
Bob       13900002222     bob@mail.com            Friend
Carol     15000003333     carol@mail.com          Coworker
Zhao     18600004444     zhaoliu@mail.com         Family

--- Group: Coworker ---
Alice  13800001111  alice@mail.com
Carol  15000003333  carol@mail.com

Found Bob: 13900002222 bob@mail.com

--- After Deleting Carol ---
Name     Phone           Email                    Group
---------------------------------------------------------
Alice    13800001111     alice@mail.com        Coworker
Bob       13900002222     bob@mail.com            Friend
Zhao     18600004444     zhaoliu@mail.com         Family

Saved to contacts.dat

3. Key Patterns Review

(1) The Dynamic Array Pattern

Both projects use the same dynamic array pattern:

  1. Struct contains data pointer + count + capacity
  2. init allocates initial memory
  3. add checks capacity and uses realloc to expand when full
  4. free releases memory and sets to NULL

This is the most common way to implement dynamic collections in C. Master it once, and you can reuse it in any scenario.

(2) The File I/O Pattern

C
fprintf(fp, "%d\n", count);
// For loop
for (int i = 0; i < count; i++) {
    fprintf(fp, "field1 field2 ...\n", ...);
}

When reading, first read the count, then loop through the records. Note that %s stops at whitespace — either ensure fields don't contain spaces, or use fscanf with a fixed format.

(3) The Delete Trick

When deleting a middle element from an array, overwrite it with the last element, then count--. This avoids moving many elements but doesn't preserve order. If order matters, use memmove to shift subsequent elements forward.

Reference entries in this section: realloc free

❓ FAQ

Q Why double the capacity instead of adding 1?
A Doubling is an amortized O(1) strategy — the total number of copies is far fewer than incrementing by 1 each time. This is a classic algorithmic result, and C++ vector, Rust Vec, and Python list all use the same 2x growth factor.
Q Should I save files in binary or text format?
A Text format is readable, manually editable, and cross-platform (no endianness or alignment issues). Binary is more compact and faster to read/write but not human-readable and not portable. Text is better for learning projects; binary is better for performance-critical production code.
Q What if I need to preserve order when using the swap-with-last delete?
A Use memmove to shift elements forward: memmove(&data[i], &data[i+1], (count-i-1)*sizeof(T)). memmove handles overlapping memory safely while memcpy does not. The shift approach is O(n) but keeps everything ordered.
Q What if a name contains spaces?
A scanf with %s stops at whitespace. Use fgets to read an entire line, or use a format like %63[^\n] with fscanf, or simply agree on underscores instead of spaces. For real-world data, fgets is usually the cleanest approach.
Q How do I determine the size of my array in C?
A For a local stack array, sizeof(arr) / sizeof(arr[0]). For a pointer from malloc, there is no way — you must keep a separate count variable. That is why every dynamic array implementation stores count alongside the pointer.
Q Difference between malloc and calloc?
A malloc(bytes) allocates uninitialized memory. calloc(n, element_size) allocates and zeroes all bytes. calloc is slightly slower but perfect for struct arrays where you want all fields to start at zero.
Q Should I cast the result of malloc (in C)?
A No. malloc returns void *, which C converts to any pointer type automatically. Casting is redundant in pure C.
Q What is the difference between ++i and i++?
A Both increment i by 1, but ++i (pre-increment) returns the new value while i++ (post-increment) returns the old value. In a for loop the final value is discarded anyway, so the choice is mostly style.

▶ Example — dynamic array with 2x capacity growth

▶ Try it Yourself
TEXT
Count=2 Capacity=4: Alice 92.5, Bob 85.0

📖 Summary

📝 Exercises

  1. Add an "edit scores" feature to the student grade management system: input a student ID and new scores to update the corresponding student record
  2. Add a "search by phone number" feature to the contact manager, and change the storage to keep contacts sorted by name (maintain order on insertion)
  3. Split both projects into multi-file structures: each project should have at least a .h declaration file and a .c implementation file, with a corresponding Makefile
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏