C: Practice: Custom Types
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.
1. Project 1: Student Grade Management System
(1) Requirements
- Add students (name, ID, three subject scores)
- Display all student information
- Search by student ID
- Calculate each student's total and average score
- Sort by total score
- Save to file / load from file
- Dynamic memory management — student count is not fixed
(2) Data Structure Design
// 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
// 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
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;
}
--- 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
- Add contacts (name, phone, email, group)
- Search by name
- Filter by group
- Delete a contact
- Modify contact information
- Save to file / load from file
(2) Data Structure Design
// 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
// 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--- 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:
- Struct contains
data pointer + count + capacity initallocates initial memoryaddchecks capacity and usesreallocto expand when fullfreereleases 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
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.
❓ FAQ
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.▶ Example — dynamic array with 2x capacity growth
▶ Try it YourselfCount=2 Capacity=4: Alice 92.5, Bob 85.0
📖 Summary
- Dynamic arrays use a
pointer + count + capacitystruct, with a 2x expansion strategy - CRUD (create, read, update, delete) is the core of data management — every project revolves around these four operations
- File saving writes the record count first, then each record; reading loads the count first, then each record
- Deleting a middle element can use swap-with-last (fast but unordered) or shift (order-preserving)
- Combining structs, dynamic memory, and file I/O is the fundamental pattern for C projects
📝 Exercises
- Add an "edit scores" feature to the student grade management system: input a student ID and new scores to update the corresponding student record
- 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)
- Split both projects into multi-file structures: each project should have at least a
.hdeclaration file and a.cimplementation file, with a corresponding Makefile