蓝色天空网mbsky.com · 知识 · 实践 · 创造C · 本地阅读预览
教程 / 编程语言 / C

C 结构体

全面讲解 C 语言结构体的定义与 typedef、嵌套/自引用与前向不完整声明、初始化与成员访问(. 与 ->)、按值与按指针传参差异,以及 sizeof 内存对齐填充与 offsetof 偏移实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

结构体定义、typedef、嵌套与前向声明

数组只能存放相同类型的元素,而结构体(`struct`)允许将不同类型的数据成员(基本类型、数组、指针乃至其他结构体)组合成一条逻辑完整的记录。例如管理图书信息时,可将 `title`、`author`、`subject` 与 `book_id` 封装在同一结构体类型中。

结构体一般形式为 `struct tag { member-list } variable-list;`,通常标签 `tag`、成员列表与变量列表三者中至少出现两项。需注意类型兼容性:两个即便成员列表完全相同的匿名结构体与具名结构体(如 `struct { int a; char b; double c; } s1;` 与 `struct SIMPLE`)在 C 中仍被视为互不兼容的独立类型,不能直接相互赋指针。使用 `typedef struct { ... } Simple2;` 则可省去每次声明变量时重复书写 `struct` 关键字。

结构体支持三类组合关系:直接嵌套其他已完整定义的结构体成员;包含指向自身类型的指针成员(`struct NODE *next_node;`,构成链表、二叉树等动态数据结构的基础);以及当 `struct A` 与 `struct B` 互相持有对方指针时,先对后者写出前向不完整声明 `struct B;`,再依次完整定义两者。

初始化、成员访问、函数传参与结构体指针

结构体变量既可在定义时按成员顺序用花括号列表初始化(C99/C11 还支持 `.book_id = 123456` 风格的指定初始化器),也可先声明变量再用点运算符 `.` 逐一读写成员(对字符数组成员应使用 `strcpy`/`snprintf` 拷贝内容而非直接用 `=` 对数组名赋值)。

结构体可直接作为函数参数传递:按值传参(`void printBook(struct Books book)`)会复制整个结构体,函数内修改副本不影响原对象,但结构体较大时会带来拷贝开销;实际工程更常用指向结构体的指针(`struct Books *ptr = &Book1;`),通过箭头运算符 `ptr->title`(等价于 `(*ptr).title`)高效访问或原地修改成员(若只读访问建议声明为 `const struct Books *`)。

结构体大小计算、内存对齐填充与 offsetof

使用 `sizeof` 运算符配合 `%zu` 可查询结构体总字节大小,该数值包含所有成员字节以及编译器为了满足 CPU 自然边界对齐要求而插入的**填充字节(Padding)**。例如 `struct Person { char name[20]; int age; float height; };` 因 `20` 恰好是 `4` 的倍数,无额外填充,总大小为 `28` 字节(`offsetof(age)==20`、`offsetof(height)==24`);而 `struct Padded { char a; int b; char c; };` 会因 4 字节对齐填充至 `12` 字节,只需按成员对齐要求从大到小重排为 `{ int b; char a; char c; }` 即可缩减为 `8` 字节。需要精确核查布局时可使用标准 `<stddef.h>` 的 `offsetof(type, member)` 宏(仅在与硬件寄存器或网络协议帧精确按字节对接时才审慎考虑 GCC 扩展 `__attribute__((packed))`)。本站已在 GCC C11 容器完整实测上述全部用例。

实测 C11 结构体初始化、值传与指针箭头访问、链表/互引用及 sizeof/offsetof 对齐填充

c · 阅读源码
#include <stddef.h>
#include <stdio.h>
#include <string.h>

struct Book {
    char title[50];
    char author[50];
    char subject[100];
    int book_id;
};

struct Simple {
    int a;
    char b;
    double c;
};

struct Complex {
    char label[16];
    struct Simple inner;
};

struct Node {
    int value;
    struct Node *next;
};

struct PartnerB;
struct PartnerA {
    int id;
    struct PartnerB *peer;
};
struct PartnerB {
    int id;
    struct PartnerA *peer;
};

struct Person {
    char name[20];
    int age;
    float height;
};

struct Padded {
    char a;
    int b;
    char c;
};

struct Compact {
    int b;
    char a;
    char c;
};

static void mutate_book_by_value(struct Book copy) {
    copy.book_id = 999999;
    (void)copy;
}

static void update_book_by_ptr(struct Book *ptr, int new_id) {
    ptr->book_id = new_id;
}

int main(void) {
    struct Book b0 = {"C Language", "MBSKY", "Systems", 123456};
    struct Book b1;
    strcpy(b1.title, "C Programming");
    strcpy(b1.author, "Ada");
    strcpy(b1.subject, "Core C");
    b1.book_id = 6495407;
    int c1_pass = (strcmp(b0.title, "C Language") == 0 && b0.book_id == 123456 &&
                   strcmp(b1.title, "C Programming") == 0 && b1.book_id == 6495407);

    mutate_book_by_value(b1);
    int after_val = b1.book_id;
    update_book_by_ptr(&b1, 6495700);
    int after_ptr = b1.book_id;
    int c2_pass = (after_val == 6495407 && after_ptr == 6495700);

    struct Complex cx = {"wrap", {7, 'K', 2.5}};
    struct Node n3 = {30, NULL};
    struct Node n2 = {20, &n3};
    struct Node n1 = {10, &n2};
    int list_sum = 0;
    for (struct Node *cur = &n1; cur != NULL; cur = cur->next) {
        list_sum += cur->value;
    }
    struct PartnerA pa = {1, NULL};
    struct PartnerB pb = {2, &pa};
    pa.peer = &pb;
    int mutual_ok = (pa.peer->id == 2 && pb.peer->id == 1);
    int c3_pass = (cx.inner.a == 7 && list_sum == 60 && mutual_ok);

    size_t sz_person = sizeof(struct Person);
    size_t off_age = offsetof(struct Person, age);
    size_t off_height = offsetof(struct Person, height);
    size_t sz_padded = sizeof(struct Padded);
    size_t sz_compact = sizeof(struct Compact);
    int c4_pass = (sz_person == 28 && off_age == 20 && off_height == 24 &&
                   sz_padded == 12 && sz_compact == 8);

    printf("{\"runtime\": \"GCC C11 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [\n");
    printf("  {\"name\": \"struct_init_and_dot_access\", \"expected\": {\"b0_id\": 123456, \"b1_id\": 6495407}, \"actual\": {\"b0_id\": %d, \"b1_id\": %d}, \"passed\": %s},\n",
           b0.book_id, 6495407, c1_pass ? "true" : "false");
    printf("  {\"name\": \"struct_value_vs_pointer_arrow\", \"expected\": {\"after_value\": 6495407, \"after_ptr\": 6495700}, \"actual\": {\"after_value\": %d, \"after_ptr\": %d}, \"passed\": %s},\n",
           after_val, after_ptr, c2_pass ? "true" : "false");
    printf("  {\"name\": \"nested_self_ref_and_forward_decl\", \"expected\": {\"nested_a\": 7, \"list_sum\": 60, \"mutual\": true}, \"actual\": {\"nested_a\": %d, \"list_sum\": %d, \"mutual\": %s}, \"passed\": %s},\n",
           cx.inner.a, list_sum, mutual_ok ? "true" : "false", c3_pass ? "true" : "false");
    printf("  {\"name\": \"sizeof_padding_and_offsetof\", \"expected\": {\"person\": 28, \"off_age\": 20, \"off_height\": 24, \"padded\": 12, \"compact\": 8}, \"actual\": {\"person\": %zu, \"off_age\": %zu, \"off_height\": %zu, \"padded\": %zu, \"compact\": %zu}, \"passed\": %s}\n",
           sz_person, off_age, off_height, sz_padded, sz_compact, c4_pass ? "true" : "false");
    printf("]}\n");
    return 0;
}
预期结果 · 待实际运行核验
  • 确认初始化与点访问、按值传参不改原 id(6495407) 而指针箭头更新为 6495700、3 节点链表求和 60 与互引用成功、Person 占 28 字节且重排成员使结构体从 12 字节降至 8 字节。
实测 C11 结构体初始化、值传与指针箭头访问、链表/互引用及 sizeof/offsetof 对齐填充

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC 13.3.0 C11 linux/amd64,--network none)。

当前源码 SHA256:48061f5f6e04644669533a7e7092d9295c2ad2ea3b26c1c7bf3ffcb4f6fd9c34

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载C 结构体实验

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC 13.3.0 C11 linux/amd64,--network none)。

ZIP SHA256:9462a67a8dea93b1746196d4525c658f868041944e54f9af7375ae71b9d38cc4

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

结构体 `struct A { char c1; int x; char c2; };` 与 `struct B { int x; char c1; char c2; };` 成员完全相同,为什么在 64 位常见平台上 `sizeof(struct A)` 是 12 字节而 `sizeof(struct B)` 只有 8 字节?

展开参考解答

编译器按成员自然对齐要求(`int` 需 4 字节对齐)和结构体整体对齐(最大成员对齐的整数倍)插入填充字节:`struct A` 在 `c1` 后补 3 字节、在 `c2` 后再补 3 字节共 12 字节;`struct B` 将 `int` 放首位后两 `char` 紧邻存放仅末尾补 2 字节,共 8 字节。

规范与官方依据