📘结构体进阶

2026-08-18
⭐⭐ GESP 6级

📖概念讲解

结构体进阶是 GESP 6 级核心考点,属于数据类型与内存管理类别。

核心内容:结构体嵌套、结构体数组、结构体指针、结构体做函数参数。

⚡ 核心机制:
• 结构体嵌套:一个结构体的成员可以是另一个结构体(包含关系)
• 结构体数组:存储多个同类结构体变量,类似二维数组的概念
• 结构体指针:Student *p = &s;,访问成员用 p->name(箭头运算符)
• 函数传参:传结构体指针可以避免拷贝,效率更高

易错点:

💻代码示例

1#include <iostream>
2#include <string>
3using namespace std;
4
5// 定义地址结构体(被嵌套的那个)
6struct Address {
7 string city;
8 string street;
9};
10
11// 定义学生结构体(嵌套了 Address)
12struct Student {
13 string name;
14 int score;
15 Address addr; // 嵌套结构体成员
16};
17
18// 函数参数用结构体指针,避免拷贝整个结构体
19void printStudent(const Student *p) { // const 指针:只读不改
20 cout << "姓名: " << p->name; // 指针用箭头 -> 访问成员
21 cout << ", 分数: " << p->score;
22 cout << ", 城市: " << p->addr.city; // 嵌套访问:p->addr.city
23 cout << endl;
24}
25
26int main() {
27 // 结构体数组:存储 3 个学生
28 Student stu[3] = {
29 {"小明", 95, {"北京", "中关村"}}, // 嵌套用两层花括号
30 {"小红", 88, {"上海", "浦东"}},
31 {"小刚", 76, {"广州", "天河"}}
32 };
33
34 // 用指针遍历结构体数组
35 Student *p = stu; // 数组名就是首元素指针
36 for (int i = 0; i < 3; i++) {
37 printStudent(p + i); // 指针偏移访问每个学生
38 }
39 return 0;
40}
41// 输出: 姓名: 小明, 分数: 95, 城市: 北京
42// 姓名: 小红, 分数: 88, 城市: 上海
43// 姓名: 小刚, 分数: 76, 城市: 广州

🧩互动小测

第 1 题:结构体指针访问成员用什么运算符?

第 2 题:以下嵌套初始化哪个是正确的?

第 3 题:结构体做函数参数时,默认传递方式是?

🏋️动手练一练

📝 编程练习

题目:学生成绩排名
定义一个 Student 结构体,包含 name(字符串)、score(整数)、city(字符串)三个成员。
输入 n 个学生信息,按分数从高到低排序后输出。

输入:
3
小明 95 北京
小红 88 上海
小刚 76 广州


输出:
小明 95 北京
小红 88 上海
小刚 76 广州


提示:用结构体数组存储,可以用 sort 配合自定义比较函数,或手写冒泡排序。
参考答案:
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int score;
    string city;
};

int main() {
    int n;
    cin >> n;
    Student stu[100];  // 结构体数组,最多100人
    for (int i = 0; i < n; i++) {
        cin >> stu[i].name >> stu[i].score >> stu[i].city;
    }
    // 冒泡排序:按分数从高到低
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (stu[j].score < stu[j+1].score) {
                Student temp = stu[j];      // 交换整个结构体
                stu[j] = stu[j+1];
                stu[j+1] = temp;
            }
        }
    }
    for (int i = 0; i < n; i++) {
        cout << stu[i].name << " " << stu[i].score << " " << stu[i].city << endl;
    }
    return 0;
}

要点:结构体可以整体赋值和交换(temp = stu[j]),这是考试高频考点。排序时注意比较的是哪个成员。

📝易错点提醒

学完这个知识点后点一下