第6天:C语言中的结构体:在没有类的情况下组织数据

发布: (2026年1月13日 GMT+8 23:45)
2 分钟阅读
原文: 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:

Back to Blog

相关文章

阅读更多 »

React 应用基础

介绍 今天我们将探讨在创建 React 应用时可见的文件和文件夹的原因和用途。 !React app structure https:/...

适合初学者的 Rust 入门方式

介绍 Rust 是一种强大的语言,但对初学者来说,入门可能会感到不知所措。当我开始学习 Rust 时,我意识到我需要一个简单的、...

构建主要 Web 浏览器列表

概述:在周末完成两套相当厚重的理论课程并撰写相关内容后,能够回到 freeCodeCamp,真是松了一口气……