C语言:结构体

一、结构体的概念和定义

1. 为什么要定义结构体

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

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

2. 结构体定义的格式

struct [结构体名]{

成员列表

};

比如:

cpp 复制代码
struct Student{
    char num[10];
    char name[10];
    int score;
};    //别忘记分号

结构体也可以嵌套定义:

cpp 复制代码
struct Birthday{
    int year;
    int month;
    int day;
};
struct Student{
    char num[10];
    char name[10];
    int score;
    struct Birthday;    //嵌套
};

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

1. 结构体变量的定义

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

cpp 复制代码
struct Student{              //定义结构体类型
    char num[10];
    char name[10];
    int score;
    struct Birthday;
}
int main()
{
    struct Student p1,p2;    //定义两个结构体变量
    ...
}

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

cpp 复制代码
int main()
{
    struct Student{
        char num[10];
        char name[10];
        int score;
        struct Birthday;
    };                        //定义了结构体类型
    struct Student p1,p2;     //定义了结构体变量
    ...
}

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

cpp 复制代码
int main()
{
    struct Student{
        char num[10];
        char name[10];
        int score;
        struct Birthday;
    }p1,p2;        //定义了结构体类型,同时定义了结构体变量
    ...
}

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

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

三、结构体变量的初始化

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

cpp 复制代码
struct Student{
    char num[10];
    cahr name[10];
    int score;
    struct Birthday;
}p1,p2={"122209","zhangsan",100,1996,12,20};
struct Student p3={"200010","lisi",20};

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

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

cpp 复制代码
struct Student{
    char num[10];
    char name[10];
    int score;
    struct Birthday;
};
struct Student s[10];
//也可以在定义的时候初始化
struct Student s[10]={{"001","wang",78},{"002","li"}};
//未初始化的成员和数组元素自动被设置为0
相关推荐
Alberta ゙21 小时前
C++初阶
开发语言·c++
the白勺1 天前
RabbitMQ-基础-总结
开发语言·c#
弘毅 失败的 mian1 天前
编译和链接
c语言·经验分享·笔记·编程入门
Dev7z1 天前
基于Matlab多目标粒子群优化的无人机三维路径规划与避障研究
开发语言·matlab·无人机
沐知全栈开发1 天前
HTML 脚本:基础、应用与未来趋势
开发语言
@菜菜_达1 天前
interact.js 前端拖拽插件
开发语言·前端·javascript
APIshop1 天前
实战解析:苏宁易购 item_search 按关键字搜索商品API接口
开发语言·chrome·python
百***92021 天前
java进阶1——JVM
java·开发语言·jvm
蓝桉~MLGT1 天前
Python学习历程——Python面向对象编程详解
开发语言·python·学习
Evand J1 天前
【MATLAB例程】2雷达二维目标跟踪滤波系统-UKF(无迹卡尔曼滤波)实现,目标匀速运动模型(带扰动)。附代码下载链接
开发语言·matlab·目标跟踪·滤波·卡尔曼滤波