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
相关推荐
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329292 天前
Day03_刷题niuke20250915
c语言
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法