结构体与联合体
struct/union、链表直觉。
30 分钟
结构体与联合体
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 | 有 | 有 |
| 继承 |