[C 语言] 嵌套结构体

结构体理解:

起始结构体就是一个类型,而用这个类型下有不同的成员。 每个成员在共同的类型下有相同的属性。
比如有一个班级的类,班级的类下有学生这种类型,而不同的学生有名字,年龄,班级信息这种属性。学生的班级属性中含有很多班级信息,这时候就要用到结构体嵌套。

复制代码
#include <stdio.h>
#include <string.h> // 用于字符串操作
#include <stdlib.h> // 解决malloc和free的声明问题

// 定义班级结构体
typedef struct {
    char className[50];
    char headTeacher[50];
} Class;

// 定义学生结构体,其中嵌套了班级结构体
typedef struct {
    char name[50];
    int age;
    Class classInfo; // 结构体嵌套,直接包含一个Class类型的成员
} Student;

int main() {
    // 创建班级实例
    Class class1 = {"三年级一班", "张老师"};

    // 创建学生实例,并初始化嵌套的班级信息
    Student student1 = {"小明", 10, class1};

    // 或者动态创建学生实例
    Student* student2 = (Student*)malloc(sizeof(Student));
    strcpy(student2->name, "小红");
    student2->age = 11;
    strcpy(student2->classInfo.className, "三年级二班");
    strcpy(student2->classInfo.headTeacher, "李老师");


    printf("学生姓名: %s, 年龄: %d, 所在班级: %s, 班主任: %s\n",
    student1.name, student1.age, student1.classInfo.className,
    student1.classInfo.headTeacher);

    if(student2 != NULL) {
        printf("学生姓名: %s, 年龄: %d, 所在班级: %s, 班主任: %s\n",
           student2->name, student2->age, student2->classInfo.className, 
            student2->classInfo.headTeacher);
     free(student2); // 动态分配的内存记得释放
    }
}

输出:

学生姓名: 小明, 年龄: 10, 所在班级: 三年级一班, 班主任: 张老师

学生姓名: 小红, 年龄: 11, 所在班级: 三年级二班, 班主任: 李老师

相关推荐
祈安_2 天前
C语言内存函数
c语言·后端
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法