12 · 结构体 struct

2026.09.27 · 🟡 中(≈ Java 的类,但没方法)

把不同类型的数据打包成一个整体 —— 相当于 Java 的 POJO / DTO,但没有方法、没有继承。

定义与使用

struct Student {
    char name[20];cccccc
    int  age;
    float score;
};

struct Student s1;                    // 声明
strcpy(s1.name, "Tom");               // 字符数组要用 strcpy 赋值
s1.age = 18;
s1.score = 95.5;

printf("%s %d %.1f\n", s1.name, s1.age, s1.score);

初始化

struct Student s2 = {"Jerry", 19, 88.0};       // 按顺序
struct Student s3 = {.age = 20, .score = 90}; // C99 指定成员

用指针访问结构体(关键)

struct Student *p = &s1;
printf("%s\n", (*p).name);   // 先解引用再取成员 —— 写法啰嗦
printf("%s\n", p->name);     // ✅ 箭头运算符,等价于上面

-> 就是「指针访问成员」的简写:p->name ≡ (*p).name

结构体数组

struct Student list[3] = {
    {"Tom", 18, 95.5},
    {"Jerry", 19, 88.0},
    {"Lucy", 20, 91.0}
};
for (int i = 0; i < 3; i++)
    printf("%s: %.1f\n", list[i].name, list[i].score);

结构体作函数参数

void printStudent(struct Student s);           // 传值:拷贝整个结构体(大结构体费性能)
void printStudent2(const struct Student *s);   // ✅ 传指针:高效,只传地址

实践:结构体较大时一律传指针,并加 const 防止被改。

typedef 简化写法(推荐)

typedef struct Student {
    char name[20];
    int  age;
} Student;              // 以后直接写 Student s1;

见 13-共用体-位域-枚举-typedef

⚡ Java 对比

Java C
定义 class struct
方法 有 无(只能另写函数操作它)
继承 有 无
访问 . .(值)或 ->(指针)
内存 堆上对象 栈上/堆上(可 malloc)

关联

09-指针 · 13-共用体-位域-枚举-typedef · 19-内存管理 · 15-文件读写