• C语言:结构体


    一、结构体的概念和定义

    1. 为什么要定义结构体

    结构体是由用户自己定义(设计)的数据类型

    其实就是各种信息的打包。比如说,每个学生都有学号、姓名和成绩,100个学生就有100份这种数据,打包起来整合就会方便很多。

    2. 结构体定义的格式

    struct [结构体名]{

            成员列表

    };

    比如:

    1. struct Student{
    2. char num[10];
    3. char name[10];
    4. int score;
    5. }; //别忘记分号

    结构体也可以嵌套定义:

    1. struct Birthday{
    2. int year;
    3. int month;
    4. int day;
    5. };
    6. struct Student{
    7. char num[10];
    8. char name[10];
    9. int score;
    10. struct Birthday; //嵌套
    11. };

    二、结构体变量的定义和空间分配

    1. 结构体变量的定义

    (1)先定义结构体,再定义结构体变量

    1. struct Student{ //定义结构体类型
    2. char num[10];
    3. char name[10];
    4. int score;
    5. struct Birthday;
    6. }
    7. int main()
    8. {
    9. struct Student p1,p2; //定义两个结构体变量
    10. ...
    11. }

     也可以把结构体定义放在main()函数中:

    1. int main()
    2. {
    3. struct Student{
    4. char num[10];
    5. char name[10];
    6. int score;
    7. struct Birthday;
    8. }; //定义了结构体类型
    9. struct Student p1,p2; //定义了结构体变量
    10. ...
    11. }

    (2)定义结构体的同时定义结构体变量

    1. int main()
    2. {
    3. struct Student{
    4. char num[10];
    5. char name[10];
    6. int score;
    7. struct Birthday;
    8. }p1,p2; //定义了结构体类型,同时定义了结构体变量
    9. ...
    10. }

    2. 结构体变量的空间分配

    系统给结构体变量分配空间时,按照成员在结构体的定义顺序依次给每一个成员分配空间。结构体变量所占空间的总字节数等于每个成员所占字节数之和。

    三、结构体变量的初始化

    定义结构体变量时,可以对其初始化。

    1. struct Student{
    2. char num[10];
    3. cahr name[10];
    4. int score;
    5. struct Birthday;
    6. }p1,p2={"122209","zhangsan",100,1996,12,20};
    7. struct Student p3={"200010","lisi",20};

    四、结构体数组的定义和初始化

    若程序中需要若干结构体变量,可以把它们定义成数组。

    1. struct Student{
    2. char num[10];
    3. char name[10];
    4. int score;
    5. struct Birthday;
    6. };
    7. struct Student s[10];
    8. //也可以在定义的时候初始化
    9. struct Student s[10]={{"001","wang",78},{"002","li"}};
    10. //未初始化的成员和数组元素自动被设置为0

     

  • 相关阅读:
    ML之shap:分析基于shap库生成的力图、鸟瞰图、散点图等可视化图的坐标与内容详解之详细攻略
    外包干了4年,技术退步明显.......
    在Node.js中,什么是事件发射器(EventEmitter)?
    算法---树状数组
    SpringBoot原理-自动配置-案例(自定义starter分析)
    刷爆力扣之等价多米诺骨牌对的数量
    小程序学习笔记
    聊天软件项目开发2
    Qt:多语言支持,构建全面应用程序“
    Oracle数据库备份与恢复exp/imp命令
  • 原文地址:https://blog.csdn.net/2302_80978287/article/details/142286012