struct Birthday{
int year;
int month;
int day;
};
//声明结构体类型
//typedef:定义新类型,为类型取别名
//typedef 原有类型,新类型
typedef struct Student{
char *name;
int age;
int code;
double score[3];
//嵌套
struct Birthday birthday;
} Student;
void printStudent(struct Student student);
void printStudents(struct Student *student,int length );
void soreStudents(Student *student,int length);
void exchangeAge(Student *student,Student *anotherstudent);
int main(int argc,const char * argv[]){
//定义结构体数组
struct Student students[5] ={
{"student1",21,1,{80,99,90},{1993, 10, 3}},
{"student2",20,2,{80,99,90},{1993, 10, 3}},
{"student3",23,3,{80,99,90},{1993, 10, 3}},
{"student4",21,4,{80,99,90},{1993, 10, 3}},
{"student5",26,5,{80,99,90},{1993, 10, 3}}};
Student *student=&students[0];
Student *anotherstudent=&student[1];
printStudent(*student);
printStudent(*anotherstudent);
printf("年龄改变了!!!\n");
exchangeAge(student, anotherstudent);
printStudent(*student);
printStudent(*anotherstudent);
return 0;
}
//打印出单个学生的信息
void printStudent(struct Student student){
printf(" name =%s age =%d code = %d score = {%.2f,%.2f,%.2f} birthday = %d.%d.%d\n",
&student,
student.name,
student.age,
student.code,
student.score[0],
student.score[1],
student.score[2],
student.birthday.year,
student.birthday.month,
student.birthday.day);
//符号写错毁一生啊,里面逗号打成分号了啊。。。
}
//打印出所有学生的信息
void printStudents(struct Student *student,int length ){
if (student == NULL && length == 0) {
return;
}
for (int i = 0; i < length; i++) {
printStudent(student[i]);
}
}
//数组的排序(根据学生的年龄)
void soreStudents(Student *student,int length){
if (student == NULL || length == 0) {
return;
}
for (int i =0; i < length; i++) {
for (int j = i; j
if (student[i].age>student[j].age) {
Student temp = student[i];
student[i] = student[j];
student[j] = temp;
}
}
}
}
void exchangeAge(Student *student,Student *anotherstudent){
if(student == NULL || anotherstudent == NULL ){
return;
}
//第一种方法
// int temp = student -> age;
// student -> age=anotherstudent -> age;
// anotherstudent -> age = temp;
//第二种方法
int temp = (*student).age;
(*student).age = (*anotherstudent).age;
(*anotherstudent).age = temp;
}
输出结果:
name =student1 age =21 code = 1 score = {80.00,99.00,90.00} birthday = 1993.10.3
name =student2 age =20 code = 2 score = {80.00,99.00,90.00} birthday = 1993.10.3
年龄改变了!!!
name =student1 age =20 code = 1 score = {80.00,99.00,90.00} birthday = 1993.10.3
name =student2 age =21 code = 2 score = {80.00,99.00,90.00} birthday = 1993.10.3
Program ended with exit code: 0