Z
ZHANK
结构体与内存

结构体基础

struct 定义与使用、成员访问、结构体传参(值 vs 指针)

结构体基础

struct 把多个不同类型的数据打包成一个整体——C 语言没有 class,struct 就是最核心的复合类型。

学完本章你将: 掌握 struct 定义/使用、成员访问、值传递 vs 指针传递。


定义结构体

c
#include <stdio.h>
#include <string.h>

// 定义结构体类型
struct Student {
    int id;
    char name[50];
    float score;
};

int main() {
    // 声明变量
    struct Student s1;

    // 赋值成员
    s1.id = 1;
    strcpy(s1.name, "小明");
    s1.score = 92.5;

    printf("学号:%d,姓名:%s,成绩:%.1f\n",
           s1.id, s1.name, s1.score);

    return 0;
}

初始化方式

c
// 声明时初始化(按顺序)
struct Student s1 = {1, "小明", 92.5};

// 指定成员初始化(C99+)
struct Student s2 = {.id = 2, .name = "小红", .score = 88.0};

// 部分初始化(其余为 0)
struct Student s3 = {.id = 3};  // name 为空,score 为 0.0

结构体传参:值 vs 指针

c
// ❌ 值传递——拷贝整个结构体(浪费时间和内存)
void print(struct Student s) {
    printf("%s\n", s.name);
}

// ✅ 指针传递——只传地址(高效)
void update(struct Student *s, float newScore) {
    s->score = newScore;  // 相当于 (*s).score
}

💡 s->score(*s).score 完全等价。-> 是指针访问结构体成员的语法糖。


typedef 简化

c
typedef struct {
    int id;
    char name[50];
} Student;   // 以后直接用 Student,不用写 struct Student

int main() {
    Student s1 = {1, "小明", 92.5};  // 简洁!
}