大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
结构体与联合体
struct 将相关数据聚合,union 共享同一块内存。对照 /roadmaps/c,本课是链表、协议解析与内核数据结构的入门。
学习目标
- 定义与使用结构体
- 理解内存对齐与
sizeof(struct) - 用结构体实现简单链表节点
- 了解
union的典型用途
核心概念
结构体与链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int id;
char name[32];
struct Node *next;
} Node;
static Node *node_create(int id, const char *name) {
Node *n = malloc(sizeof(Node));
if (!n) return NULL;
n->id = id;
strncpy(n->name, name, sizeof n->name - 1);
n->name[sizeof n->name - 1] = '\0';
n->next = NULL;
return n;
}
static void list_push_front(Node **head, Node *n) {
n->next = *head;
*head = n;
}
static void list_free(Node *head) {
while (head) {
Node *tmp = head;
head = head->next;
free(tmp);
}
}
int main(void) {
Node *head = NULL;
list_push_front(&head, node_create(1, "intro"));
list_push_front(&head, node_create(2, "types"));
for (Node *p = head; p; p = p->next) {
printf("[%d] %s\n", p->id, p->name);
}
typedef union {
int i;
float f;
char bytes[4];
} Value;
Value v;
v.i = 0x41424344;
printf("union as int=%d bytes=%c%c%c%c\n",
v.i, v.bytes[0], v.bytes[1], v.bytes[2], v.bytes[3]);
list_free(head);
printf("Node size=%zu\n", sizeof(Node));
return 0;
}
设计要点
| 概念 | 说明 |
|---|---|
| 自引用 | 结构体可含指向自身类型的指针 |
| 对齐 | 编译器插入 padding,sizeof 可能大于字段之和 |
typedef | 常配合 struct 简化类型名 |
union | 同一时刻只应有一种成员有效 |
C 无类:无构造/析构函数,初始化靠字面量 {0} 或 calloc。
与 C++/Java 对照
| 特性 | C struct | C++ class | Java class |
|---|---|---|---|
| 方法 | 无(函数分离) | 有 | 有 |
| 访问控制 | 无 public/private | 有 | 有 |
| 继承 | 无 | 有 | 有 |
| 内存布局 | 可预测 | 可预测 | JVM 管理 |
| 链表 | 手动指针 | 智能指针/list | LinkedList |
Java 的 POJO 类似 C struct + 方法;C++ 的 class 默认成员私有,struct 默认公有。
练习
- 定义
Point { double x, y; }并写函数计算两点距离 - 扩展链表:实现
find_by_id与list_size - 用
union存储「要么是 int 要么是 float」并打印 - 打印空 struct 与含
char+int的 struct 的sizeof,观察对齐
小结
struct 聚合数据,指针串联结构;union 省内存但需纪律。 下一课学习预处理器。