第6天:C语言中的结构体:在没有类的情况下组织数据
发布: (2026年1月13日 GMT+8 23:45)
2 min read
原文: Dev.to
Source: Dev.to
Introduction
在 Java 或 Python 等语言中,你会使用 类 来把数据捆绑在一起。
C 没有类;它只有更原始的东西:结构体(struct)。
结构体(structure)是我们创建自定义数据类型的方式。如果没有结构体,存储学生信息就需要分别使用多个变量:
char *name1;
int age1;
float gpa1;
使用结构体后,你可以把这些字段组合成一个 Student 类型,这也是面向对象编程中“对象”概念的前身。
Example: Defining and Using a Struct
// Day 6: Grouping chaos into order
#include
#include
// Before: Messy variables scattered everywhere
// char *name1 = "Alice"; int age1 = 20;
// After: A custom data type
// We define a blueprint called "Student"
typedef struct {
char name[50];
int age;
float gpa;
} Student;
int main() {
// Treat the data as a single "object"
// Initialize it like an array
Student s1 = {"Alice", 20, 3.8};
// Access fields using the dot operator (.)
printf("Name: %s\n", s1.name);
printf("GPA: %.2f\n", s1.gpa);
return 0;
}
View the source code on GitHub: