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
相关推荐
励志的小陈3 分钟前
C++入门
开发语言·c++
江湖中的阿龙4 分钟前
深入理解 CAS:Java 无锁并发核心原理、缺陷与应用场景详解
java·开发语言
进击的荆棘5 分钟前
C++起始之路——继承
开发语言·c++
NGC_661112 分钟前
深入解析 ConcurrentHashMap 设计思想:高并发下的线程安全哈希表
java·开发语言
子夜四时歌1 小时前
Python详细安装与环境搭建
开发语言·python
Jinkxs1 小时前
SkyWalking - Python 应用追踪:基于 skywalking-python 的埋点
开发语言·python·skywalking
大头博士先生1 小时前
【3月考】二级Python最新真题及满分代码合集(基本操作题部分)
开发语言·python
xcLeigh1 小时前
IoTDB Python原生接口全攻略:从基础读写到高级实战
开发语言·数据库·python·api·iotdb·原生接口·读写数据
User_芊芊君子1 小时前
文科生封神!Python+AI 零门槛变现:3 天造 App,指令即收入(附脉脉 AI 沙龙干货)
开发语言·人工智能·python
是Dream呀1 小时前
2025年中秋月亮只有94.91%圆?Python告诉你真相
开发语言·python·中秋节