C: Structures

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

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.

Reference entries in this section: struct

1. struct Definition and Declaration

(1) Defining a Struct Type

C
// 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

C
struct Student s1;
struct Student s2, s3;

You can also declare variables at the same time as defining the type:

C
// 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:

C
struct {
    // Variable declaration
    int width;
    // Variable declaration
    int height;
} box;
⚠️ Note: An anonymous struct cannot be used to declare new variables later. It's typically only used for one-off scenarios.


2. Struct Variable Initialization

(1) Sequential Initialization

TEXT
struct Student s1 = {"Alice", 20, 89.5};

(2) Designated Initializer (C99)

C
struct Student s2 = {.name = "Bob", .score = 92.0, .age = 21};
💡 Tip: Designated initializers don't need to follow the declaration order. Unspecified members are automatically zeroed.

(3) Partial Initialization

TEXT
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:

C
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:

TEXT
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.

💡 Tip: Mnemonic: use a dot for variables, use an arrow for pointers.

▶ Example

▶ Try it Yourself
TEXT
Title: 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.

TEXT
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);
}
TEXT
Alice 20 89.5
Bob 21 92.0
Carol 19 78.0

Traverse a struct array with a pointer:

C
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.

TEXT
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;
}
TEXT
Alice, age 20, score 89.5
⚠️ Note: Passing by value copies the entire struct. If the struct has many members or contains large arrays, the overhead is significant. Passing a pointer only copies one address.


6. Struct as Function Parameter

(1) Pass by Value

C
// Function definition
void add_score(struct Student s, float bonus) {
    s.score += bonus;
}
⚠️ Note: When passing by value, modifications inside the function affect a copy — the original variable is unchanged.

(2) Pass by Pointer

TEXT
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 Yourself
TEXT
Original 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:

TEXT
struct Student s1 = {"Alice", 20, 89.5};
struct Student s2;
s2 = s1;

(2) Comparison

⚠️ Note: Structs cannot be compared with == or !=. You must compare members individually:

C
// 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:

C
// 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);
TEXT
Birthday: 1995-06-15

▶ Example 3: Struct Arrays with Designated Initializers

▶ Try it Yourself

输出:

TEXT
1: Alice (92.5)
2: Bob (87.0)
3: Carol (95.0)

Reference entries in this section: struct

❓ FAQ

Q Why isn't sizeof for a struct equal to the sum of sizeof of each member?
A The compiler inserts padding bytes between members to align them to their natural boundary. An int needs 4-byte alignment, so if it follows a char (1 byte), the compiler adds 3 padding bytes. The #pragma pack(1) directive disables padding but reduces CPU memory access efficiency.
Q Why should we typedef a struct so often in C?
A Because in C you must write 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.
Q Can structs be compared with ==?
A No. C does not support == 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.
Q Should I pass a struct by value or by pointer?
A Generally pass by pointer — it is more efficient (avoids a copy) and lets you modify the original. For small read-only structs, pass by value is fine. For large structs, always use a const pointer (const struct Student *s) to promise no modification.
Q Why must a struct definition end with a semicolon?
A Because variable declarations can follow immediately after the closing brace. 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.
Q What is the difference between . and ->?
A . 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".
Q How do I initialize a struct in C?
A Use designated initializers: 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.
Q Why are these constructs using pre and post-increment undefined behavior?
A Expressions like 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

📝 Exercises

  1. Define struct Rectangle with width and height. Write functions float area(struct Rectangle *r) and float perimeter(struct Rectangle *r), then calculate and print the results in main
  2. Define struct Date and write a function int date_compare(struct Date *a, struct Date *b) that returns -1/0/1 indicating whether a is earlier than / equal to / later than b
  3. Define a student struct array (5 students), sort by score from highest to lowest, and print the results
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%

🙏 帮我们做得更好

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

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