ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

[C语言]结构体初识

2026/9/23 4:21:52 拓冰建站 浏览量
[C语言]结构体初识

结构体定义

        结构体是一些值的集合,被成为成员变量,结构的每个成员可以是不同类型的变量

声明:

        定义了一个结构体比如以张蓝图,不占据内存,当你创建了一个结构体变量时,才占空间.

#include<stdio.h>//struct 为结构体关键字,  student 自定义结构体名称
struct student
{//成员变量列表char  name[20];//一个名字int age;       //年龄char sex;      //性别}s1,s2,s3;         //与下面的S变量都是结构体变量,但是s1,s2,s3为全局变量//上方定义了一个自定义的结构体类型main()
{struct student s;      //创建了student 结构体局部变量为 s;}

简便写法:

利用typedef  定义别名,  把 struct student整体 定义别名为stu   ,

定义变量时,利用stu创建结构体变量即可.     此刻stu 为结构体类型

#include<stdio.h>//struct 为结构体关键字,  student 自定义结构体名称, typedef 起别名typedef struct student  
{//成员变量列表char  name[20];//一个名字int age;       //年龄char sex;      //性别}stu;         //上方定义了一个自定义的结构体类型main()
{stu s;      //把struct student 整体 取了一个新名字 stu}

结构体变量可以是标量,变量,指针,数组,其他结构体.

#include<stdio.h>//struct 为结构体关键字,  student 自定义结构体名称struct student  
{//成员变量列表char  name[20];//一个名字int age;       //年龄char sex;      //性别};         struct txt 
{//成员变量列表int a;string str; struct  student s;   //结构体变量成员char   *pc;         //指针变量成员};         main()
{struct txt t={1,"你好",{"李明",12,'男'},arr};   //struct txt t 初始化}

结构体初始化

        1.创建结构体变量时,直接赋初值

main()
{stu s={"李明",20,"男"};      //初始化结  构体变量s}

访问结构体变量

        1.结构体变量.成员变量   (访问嵌套的结构体成员,利用 .嵌套 即可)

      


main()
{struct txt t={1,"你好",{"李明",12,'男'},arr};   //struct txt t 初始化printf("%s",t.str);      //  你好printf("%s",t.s.age);   //  12
}

        2.结构体指针->成员变量

#include<stdio.h>//struct 为结构体关键字,  student 自定义结构体名称, typedef 起别名typedef struct student  
{//成员变量列表char  name[20];   //一个名字int age;           //年龄char sex;          //性别}stu;         //上方定义了一个自定义的结构体类型-----------------------------------------------------------------------------------void print(stu* ps)           //形参为 结构体stu 的指针变量 ps
{printf("%s",ps->name);       //打印结果: 李明
}main()
{stu s={"李明",12,'男'};     print(&s);              //实参 为  &s}

第二种方法比第一种方法好

因为传参数时,参数是需要压栈的,第一个传递整个结构体对象,系统开销较大,传地址则会更小

 

数据结构:

线性结构

  1.         顺序表        (一条顺序的数据)
  2.         链表           (用一条链把数据连续起来)
  3.         栈              (先进后出), 插入一个元素叫"压栈",删除一个元素叫"出栈"
  4.         队列          (先进先出)

树形数据结构

        二叉树,图