1. 结构体的定义
结构体是由一系列具有相同类型或不同类型的数据构成的数据集合,叫做结构
2. 结构体成员访问:
结构体变量 . 成员 . 成员访问符
以下两种访问方式等价:
结构体指针变量 -> 成员 -> 指向符
(*结构体指针变量).成员
内置类型
结构体类型 -> 设计新数据类型
银行卡类型 学生类型 -> 用户自定义数据类型
typedef struct 结构体名{
成员列表 (属性)
}新类型名称,*指针类型名称;3. 结构体设计中类型:嵌套结构体类型变量
4. 结构体和数组使用
#include<stdio.h> typedef struct Student { const char* name; int age; int stu_id; int score; }Student, * PStu; void show(PStu arr, int len) { for (int i = 0; i < len; i++) { printf("姓名: %5s 年龄:%5d 学号:%5d 成绩:%5d \n", arr[i].name, arr[i].age, arr[i].stu_id, arr[i].score); } } int main() { Student arr[] = { {"zs",10,1,99}, {"lisi",11,2,98}, {"ww",9,3,99} }; //1. 封装函数,三个学生信息输出 //2. 对学生成绩排名 成绩大小:由小到大排序,成绩相同的前提:按照年龄由大到小排序: //lisi zs ww show(arr, sizeof(arr) / sizeof(arr[0])); return 0; }
结构体中有结构体定义
struct FM { int hour; int f; int m; }; struct Date { int year; int month; int day; struct FM fm; }; struct Student { const char* name;//加const的原因是const 修饰*name,如果需要修改name的值的话需要定义为数组形式,这样做的好处是为了占用空间少 const char* sex; //char sex[10] 内存结构 struct Date birthday; }; int main() { struct Student s1 = { "zs","男性",{2000,3,20,{20,20,20}}}; return 0; }
结构体中直接可以重定义的方式
struct Student { char name[10]; int age; int stu_id; }; typedef struct Student Student; //定义结构体类型的指针变量 typedef struct Student* PStu; //可以用下面代码替换 //struct Student { // char name[10]; // int age; // int stu_id; //}Student,* PStu;//这两个就是重定义的简化 int main() { int a = 10; int* p = &a; //struct Student s1 = {}; Student s1 = {}; //struct Student* pstu = &s1; PStu pstu = &s1; Student s2 = {}; }
结构体的一个定义 ,在结构中定义了三个
struct Student { char name[10]; int age; int stu_id; };
typedef struct Student Student;用typedef的重定义这样可以直接用Student来定义struct Student
定义结构体类型的指针变量typedef struct Student* PStu; int main() { int a = 10; int* p = &a; //struct Student s1 = {}; Student s1 = {}; //struct Student* pstu = &s1; PStu pstu = &s1; Student s2 = {}; }
类型的设计 不占用内存空间 设计师 图纸
struct BankCard { char name[10]; int id; int password; int money; }; struct Student { char stu_name[10]; int stu_id; int age; char sex[5]; };
全局变量 -> 变量的声明 未经初始化 -> 编译器给成员列表默认值初始化//全局变量 -> 变量的声明 未经初始化 -> 编译器给成员列表默认值初始化 //struct BankCard card4;//全局变量 //int main() { struct BankCard card1 = { "招行",111,111,0 }; //根据图纸生成实体 struct BankCard card2 = { "建行",222,222,0 }; struct BankCard card3; //成员内容随机值 -> 局部变量 printf("%d", card3.id); // 不允许使用未经初始化的局部变量 struct Student stu = { "zs",1,10,"男" }; }
初识结构体
最新推荐文章于 2022-12-17 22:53:23 发布