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 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法