C语言struct类型理解学习 6.9happy birthday

C语言struct类型理解学习 6.9happy birthday,第1张

一.struct类型的存在意义

1.记录不同类型的数据(而与数组的区别是 数组是相同的数据类型组)

2.利于程序的阅读理解和移植

3.*结构体的存储方式可以提高CPU对内存的访问速度。

二.结构形式 1.一般形式
struct Information{   //声明结构
    char name[50];    //名字
    int Student id;   //学号
    float score;      //成绩
        
};

*结构声明可以放在函数外(全局结构体)or内(局部结构体,如冲突优先级大于全局结构体)

2.定义结构体变量方法
struct Information{   //声明结构
    char name[50];    //名字
    int Student id;   //学号
    float score;      //成绩
        
};
struct Information stu1;    //定义结构体变量way1
struct Information{   //声明结构
    char name[50];    //名字
    int Student id;   //学号
    float score;      //成绩
        
}stu1;    //定义结构体变量way2
3.访问结构体变量方法

一般格式:结构变量名.成员名

such as:stu1.name        //表示stu1的name

//当结构体成员为结构体时的访问方法
struct Birthday{                //声明结构体 Birthday
    int year;
    int month;
    int day;
};
struct Student{                 //声明结构体 Student
    char name[20];              
    int num;                    
    float score;                 
    struct Birthday birthday;   //生日
}stu1;

则用stu1.birthday.year 访问出生的年份。

4.结构体初始化

1.四个方法

//逐个数值
struct student stu1,stu2;
strcpy(stu1.name,"jack");    //把jack复制给结构体变量中的name
stu1.num=9;
stu1.score=89.91;    //way1  前提是要定义



stu2=(struct Student){
    "Wool",15,99.1};    //way2



struct Student{                 //声明结构体 Student
    char name[20];               
    int num;                    
    float score;                 
}stu3 = {
  "jojo", 100, 100};        //way3与定义同时  注意初始化值的类型和顺序要与结构体声明时成员的类型和顺序一致



struct Student stu4 = {.name = "king"};       //way4部分初始化


5.结构体与指针

结构指针中的值指向结构变量的首地址

1.一般形式:

struct 结构名 * 结构指针变量名

struct Student *pstu; //定义了一个指针变量,它只能指向Student结构体类型的结构体变量

结构指针变量赋值方法:pstu=&stu;        //取stu的首地址

2.通过结构指针间接访问成员值

一般形式:

(*结构指针变量). 成员名 或 结构指针变量 -> 成员名
如:

(*pstu).name    
pstu->name

 参考:(9条消息) C语言中的结构体(struct)详解_edward_zcl的博客-CSDN博客_c语言struct

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1353680.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-14
下一篇2022-06-14

发表评论

登录后才能评论

评论列表(0条)

    保存