iOS学习笔记---c语言学习第七天

时间:2023-03-08 21:55:07
 

结构体

结构体是一种自定义的数据类型

struct 结构体名

{

类型说明符  成员名;

类型说明符  成员名;

};

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{ struct teacher{
char name[];
char sex;
int age;
char course[];
};
typedef struct teacher Teacher;
Teacher cui={"cui",'m',,"language c"};
struct cup{
float price;//价格
int capacity;//容量
char corlor[];//颜色
};
typedef struct cup Cup;
Cup fuguang={10.5,,"black"};
return ;
}

结构体变量定义

由结构体类型修饰的变量叫做结构体变量
struct 结构体名 变量名={初值};
struct student stu1 = {1,“zhangsan”,‘m’,70};
结构体成员的访问
结构体变量名.成员变量名
eg:stu1.num//stu1的学号
注:结构体成员变量与普通变量一样,可以赋值
匿名结构体
结构体声明与变量的定义结合在一起
eg:struct{

int num;


char name[20];
 char sex;
 float score;


}
stu1 = {1,”wukong”, ‘m’,99.5f},
stu2 = {2, “bajie”, ‘m’, 65.0f};

iOS学习笔记---c语言学习第七天
//    struct cup{
// float price;//价格
// int capacity;//容量
// char corlor[20];//颜色
// };
// typedef struct cup Cup;
//定义结构体的同时就起别名。
// typedef struct cup{
// float price;//价格
// int capacity;//容量
// char corlor[20];//颜色
// } Cup;

iOS学习笔记---c语言学习第七天

练习:有三个学生,变成找出分数最高者以及年龄最小者。

    typedef struct students{
char name[];
int age;
float score; } Students;
Students s1={"zhangsan",,};
Students s2={"lisi",,};
Students s3={"wangwu",,};
Students max = {};
max = s1.score>s2.score?s1:s2;
max = max.score>s3.score?max:s3;
printf("%s的分数最高\n",max.name);
Students min = {};
min = s1.age<s2.age?s1:s2;
min = min.age<s3.age?min:s3;
printf("%s的年龄最小",min.name);

结构体空间占用

以最大成员变量类型所占空间为分配单位i按结构体成员声明顺序由上而下分配

注:分配空间不足以存储成员变量时,分配新的空间单位

结构体嵌套

结构体的成员依然可以是结构体
typedef struct date{
 int year;


int month;


int day; } MyDate;

struct student{

char name[20];

MyDate birthday;//stu1.birthday.year;

};

结构体数组

将多个结构体变量放到数组中,构成结构体数组

eg:struct student students[10]={0};

//练习用结构体数组做
typedef struct date{
int year;
int month;
int day;
} MyDate;
typedef struct students{
char name[];
int age;
float score;
MyDate birthday; } Students; Students stus[]={
{"zhangsan",,,{,,}},
{"lisi",,,{,,}},
{"wangwu",,,{,,}}
};
Students min= stus[];
for (int i = ; i<; i++) {
if (min.age>stus[i].age) {
min = stus[i];
}
}
printf("%s\n",min.name);
Students max = stus[];
for (int i=; i<; i++) {
if (max.score<stus[i].score) {
max = stus[i];
}
}
printf("%s",max.name);

对上述学生成绩从大到小排序

    for (int i=; i<; i++) {
for (int j=; j<-i; j++) {
if (stus[j].score>stus[j+].score) {
Students temp=stus[j];
stus[j]=stus[j+];
stus[j+]=temp;
}
}
}
for (int i=; i<; i++) {
printf("%s %d %.2f\n",stus[i].name,stus[i].age,stus[i].score);
}

排序写到函数内

typedef struct date{
int year;
int month;
int day;
} MyDate;
typedef struct students{
char name[];
int age;
float score;
MyDate birthday; } Students;
void bobbleSart(Students s[],int count)
{
for (int i=; i<count-; i++) {
for (int j=; j<count--i; j++) {
if (s[j].score>s[j+].score) {
Students temp=s[j];
s[j]=s[j+];
s[j+]=temp;
}
}
} }

总结

结构体是一种比较灵活的数据结构类型,并且与oc要学的类很相似

结构体和数组的互相嵌套可以实现比较复杂 的数据结构