C: Structures
A struct is like a custom form — it packages different types of information (name, age, grade) together into a single unit you can manage as a whole.
1. struct Definition and Declaration
(1) Defining a Struct Type
// Struct/enum/union definition
struct Student {
char name[20];
// Variable declaration
int age;
// Variable declaration
float score;
};
This defines a type struct Student. Note that the trailing semicolon is required.
(2) Declaring Struct Variables
struct Student s1;
struct Student s2, s3;
You can also declare variables at the same time as defining the type:
// Struct/enum/union definition
struct Point {
// Variable declaration
int x;
// Variable declaration
int y;
} p1, p2;
(3) Anonymous Struct
If you only need it once, you can omit the type name:
struct {
// Variable declaration
int width;
// Variable declaration
int height;
} box;
2. Struct Variable Initialization
(1) Sequential Initialization
struct Student s1 = {"Alice", 20, 89.5};
(2) Designated Initializer (C99)
struct Student s2 = {.name = "Bob", .score = 92.0, .age = 21};
(3) Partial Initialization
struct Student s3 = {"Carol"};
name is initialized; the remaining members are automatically set to 0.
3. Member Access
(1) Dot Operator .
Access members through a struct variable:
struct Student s = {"Zhao", 19, 78.5};
// I/O operation
printf("Name: %s\n", s.name);
// I/O operation
printf("Age: %d\n", s.age);
s.score = 85.0;
(2) Arrow Operator ->
Access members through a struct pointer:
struct Student s = {"Zhao", 19, 78.5};
struct Student *ps = &s;
printf("Name: %s\n", ps->name);
ps->age = 20;
ps->name is equivalent to (*ps).name. The -> operator is syntactic sugar — more concise when working with pointers.
▶ Example
▶ Try it YourselfTitle: The C Programming Language
Author: K&R
Price: 45.0
After discount: 55.0
4. Struct Array
Place multiple structs in an array for unified management.
struct Student class[3] = {
{"Alice", 20, 89.5},
{"Bob", 21, 92.0},
{"Carol", 19, 78.0}
};
for (int i = 0; i < 3; i++) {
printf("%s %d %.1f\n", class[i].name, class[i].age, class[i].score);
}
Alice 20 89.5
Bob 21 92.0
Carol 19 78.0
Traverse a struct array with a pointer:
struct Student *p = class;
// For loop
for (int i = 0; i < 3; i++, p++) {
// I/O operation
printf("%s %.1f\n", p->name, p->score);
}
5. Struct Pointer
The most common use of struct pointers: avoid copying the entire struct when passing it between functions.
void print_student(struct Student *ps) {
printf("%s, age %d, score %.1f\n", ps->name, ps->age, ps->score);
}
int main(void) {
struct Student s = {"Alice", 20, 89.5};
print_student(&s);
return 0;
}
Alice, age 20, score 89.5
6. Struct as Function Parameter
(1) Pass by Value
// Function definition
void add_score(struct Student s, float bonus) {
s.score += bonus;
}
(2) Pass by Pointer
void add_score(struct Student *s, float bonus) {
s->score += bonus;
}
Modifications through the pointer inside the function directly affect the original variable.
▶ Example
▶ Try it YourselfOriginal total: 243
After bonus: 258
7. Struct Assignment and Comparison
(1) Assignment
Structs of the same type can be directly assigned — members are copied one by one:
struct Student s1 = {"Alice", 20, 89.5};
struct Student s2;
s2 = s1;
(2) Comparison
== or !=. You must compare members individually:
// Function definition
int equal(struct Student *a, struct Student *b) {
// Return result
return a->age == b->age && a->score == b->score;
}
8. Nested Structs
A struct member can itself be another struct:
// Struct/enum/union definition
struct Date {
// Variable declaration
int year;
// Variable declaration
int month;
// Variable declaration
int day;
};
// Struct/enum/union definition
struct Employee {
char name[20];
struct Date birthday;
// Variable declaration
float salary;
};
struct Employee e = {"Chen", {1995, 6, 15}, 8000.0};
// I/O operation
printf("Birthday: %d-%02d-%02d\n", e.birthday.year, e.birthday.month, e.birthday.day);
Birthday: 1995-06-15
▶ Example 3: Struct Arrays with Designated Initializers
▶ Try it Yourself输出:
TEXT1: Alice (92.5) 2: Bob (87.0) 3: Carol (95.0)
❓ FAQ
#pragma pack(1) directive disables padding but reduces CPU memory access efficiency.struct Student every time unless you typedef it. typedef struct Student Student lets you write just Student. This is purely syntactic sugar with zero runtime cost. C++ removed the need for typedef — you can write Student directly — but C never did.== for structs. You must compare members individually, or use memcmp which is not fully reliable because padding bytes are uninitialized and vary between compilers. C++ lets you overload operator== for structs, but C has no such feature.const struct Student *s) to promise no modification.struct Point { int x; int y; } origin; defines both the type and a variable. The semicolon tells the compiler the declaration list is complete. Omitting it causes a syntax error that is confusing for beginners.. accesses a member through a struct variable; -> accesses through a struct pointer. p->name is shorthand for (*p).name. Choosing the wrong one causes a compile error with "incomplete type" or "request for member in something not a structure".struct Student s = { .id = 1, .name = "Alice", .age = 20 };. Missing members are zero-initialized. Before C99, only sequential initialization was allowed and all members had to be covered in order.a[i] = i++ or ++i = i++ modify the same object more than once between sequence points. C does not specify the order of evaluation, so the compiler can pick any order — different compilers or optimization levels can produce different results. The behavior is undefined per the C standard.📖 Summary
structpackages members of different types into a custom type- Initialization can use sequential values or C99 designated initializers
.name = ... - Use
.to access members through a variable,->through a pointer - Struct arrays allow batch management of same-type data
- Prefer passing struct pointers as function parameters to avoid copy overhead
- Structs can be nested — a member can itself be a struct
📝 Exercises
- Define
struct Rectanglewith width and height. Write functionsfloat area(struct Rectangle *r)andfloat perimeter(struct Rectangle *r), then calculate and print the results in main - Define
struct Dateand write a functionint date_compare(struct Date *a, struct Date *b)that returns -1/0/1 indicating whether a is earlier than / equal to / later than b - Define a student struct array (5 students), sort by score from highest to lowest, and print the results