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语言)
c语言·开发语言·数据结构
Maybe_ch4 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨4 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王4 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php
快乐飒男4 小时前
哈希表(c语言)
c语言·哈希算法·散列表
Edingbrugh.南空5 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
CodeCraft Studio5 小时前
借助Aspose.HTML控件,在 Python 中将 HTML 转换为 Markdown
开发语言·python·html·markdown·aspose·html转markdown·asposel.html
QQ_4376643145 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
aramae5 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
封奚泽优6 小时前
使用Python实现单词记忆软件
开发语言·python·random·qpushbutton·qtwidgets·qtcore·qtgui