🏗️ Structs & Data Organization结构体与数据组织

Organize complex data with structs for abstraction用结构体组织复杂数据,实现数据抽象

What is a Struct?什么是结构体?

A struct is a composite data type in C that groups fields of different types into a logical whole. It predates the idea of “classes” in OOP and is useful for modeling entities. 结构体(struct)是 C 语言中的一种复合数据类型,它允许我们将不同类型的数据组合在一起,形成一个逻辑整体。它是面向对象编程中“类”概念的前身,适合建模实体。

Struct Memory Layout Example:结构体内存布局示例:
+------------------+
|    red (int)     |  偏移量: 0字节
+------------------+
|   green (int)    |  偏移量: 4字节
+------------------+
|    blue (int)    |  偏移量: 8字节
+------------------+
|  总大小: 12字节  |
+------------------+
                
// 定义RGB颜色结构体 struct rgb { int red; // 红色分量 (0-255) int green; // 绿色分量 (0-255) int blue; // 蓝色分量 (0-255) };

结构体的基本操作

1. 声明结构体变量

struct rgb color1; // 声明结构体变量 struct rgb color2 = {255, 128, 0}; // 声明并初始化

2. 访问结构体成员

struct rgb my_color; my_color.red = 255; // 设置红色分量 my_color.green = 128; // 设置绿色分量 my_color.blue = 0; // 设置蓝色分量 printf("RGB: %d, %d, %d\n", my_color.red, my_color.green, my_color.blue);

3. 结构体指针

struct rgb color = {10, 20, 30}; struct rgb *ptr = &color; // 结构体指针 // 使用箭头运算符访问成员 ptr->red = 100; // 等价于 (*ptr).red = 100 ptr->green = 200; // 等价于 (*ptr).green = 200

💡 点运算符 vs 箭头运算符

  • . (dot): access members via a struct variable. (点运算符): 用于结构体变量访问成员
  • -> (arrow): access members via a struct pointer-> (箭头运算符): 用于结构体指针访问成员
  • ptr->member is equivalent to (*ptr).memberptr->member 等价于 (*ptr).member

结构体作为函数参数

Structs can be passed to functions; be mindful of copying vs passing by pointer.结构体可以作为函数参数传递,但要注意传递方式的不同:

// 值传递:会复制整个结构体 void print_color(struct rgb color) { printf("RGB: %d, %d, %d\n", color.red, color.green, color.blue); } // 指针传递:更高效,可以修改原结构体 void change_color(struct rgb *color) { int temp = color->red; color->red = color->blue; color->blue = color->green; color->green = temp; }

🎯 RGB Struct Conversion ExampleRGB结构体转换实例

Let’s refactor the previous RGB conversion using a struct:让我们用结构体重构之前的RGB颜色转换函数:

// 定义RGB结构体 struct rgb { int red, green, blue; }; // 使用结构体的颜色转换函数 void change_colour_struct(struct rgb *color) { int temp = color->red; // 保存红色值 color->red = color->blue; // new red = old blue color->blue = color->green; // new blue = old green color->green = temp; // new green = old red }

结构体数组

Create arrays of structs to manage multiple related records:我们可以创建结构体数组来管理多个相关的数据:

// 定义电影评论结构体 struct movie_review { char title[100]; // 电影标题 int release_year; // 发行年份 int rating; // 评分 (0-10) }; // 创建电影评论数组 struct movie_review reviews[3] = { {"The Matrix", 1999, 9}, {"Inception", 2010, 8}, {"Interstellar", 2014, 10} }; // 访问数组中的结构体 for (int i = 0; i < 3; i++) { printf("%s (%d): %d/10\n", reviews[i].title, reviews[i].release_year, reviews[i].rating); }

⚠️ 结构体内存对齐

Compilers may insert padding for alignment; total size can exceed sum of fields.编译器可能会在结构体中插入填充字节以满足内存对齐要求,这可能导致结构体的大小大于各成员大小之和。

struct example { char c; // 1字节 int i; // 4字节 // 1字节 }; // 实际大小可能是12字节,而不是6字节

🎯 练习与巩固

练习1: 结构体基础操作

Define a student struct (name, age, score) and print it.定义一个表示学生信息的结构体,包含姓名、年龄和成绩三个字段,并实现一个函数来打印学生信息。

// 定义学生结构体 struct student { char name[50]; int age; float score; }; // 实现打印函数 void print_student(struct student s) { // 在这里实现打印逻辑 }

Answer:答案:

void print_student(struct student s) { printf("姓名: %s\n", s.name); printf("年龄: %d\n", s.age); printf("成绩: %.2f\n", s.score); } // 使用示例 int main() { struct student s1 = {"张三", 20, 85.5}; print_student(s1); return 0; }

练习2: 复杂结构体设计

Design a 2D point struct and compute distance between two points.设计一个表示二维点的结构体,并实现计算两点距离的函数。

// 定义二维点结构体 struct point2d { double x; double y; }; // 计算两点距离 double distance(struct point2d p1, struct point2d p2) { // 使用勾股定理: sqrt((x2-x1)² + (y2-y1)²) // 在这里实现距离计算 }

Answer:答案:

#include double distance(struct point2d p1, struct point2d p2) { double dx = p2.x - p1.x; double dy = p2.y - p1.y; return sqrt(dx * dx + dy * dy); } // 使用示例 int main() { struct point2d p1 = {0.0, 0.0}; struct point2d p2 = {3.0, 4.0}; double d = distance(p1, p2); printf("距离: %.2f\n", d); // 输出: 5.00 return 0; }

总结

Structs are crucial for organizing complex data. In this module, you learned:结构体是C语言中组织复杂数据的重要工具,本周我们学习了:

🚀 下一步学习

Structs enable organizing complex data. Next, we’ll learn dynamic allocation to create structs at runtime.结构体让我们能够组织复杂的数据,接下来我们将学习动态内存分配,看看如何在运行时创建结构体。