c语言中结构体指针6,C语言中的结构体指针

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值