1.定义结构体数组存储5个学生的信息:
姓名,年龄,性别
定义函数实现输入,要求形参使用结构体指针接收
函数实现5个学生年龄排序(注意对年龄排序时,交换的是所有信息)
#include <myhead.h>
#define ST_M 5 //创建宏常量,结尾没有分号“;”
typedef struct STU_Information{
char name[20];
char sex;
int age;
}SUI,*pSUI;
void input(pSUI s){
for(int i=0;i<ST_M;i++){
printf("请输入学生名字:\n");
scanf("%s",(s+i)->name);
getchar();
printf("请输入%s的年龄:\n",(s+i)->name);
scanf("%d",&(s+i)->age);
getchar();
printf("请输入%s的性别(男:M or m;女:W or w):",(s+i)->name);
scanf("%c",&(s+i)->sex);
}
}
void sort(pSUI s){
for(int i=0;i<ST_M-1;i++){
for(int j=1;j<ST_M;j++){
if( (s+i)->age < (s+j)->age){
int temp;
temp = *(s+i);
*(s+i) = *(s+j);
*(s+j) = temp;
}
}
printf("%s:%d;\t",(s+i)->name,(s+i)->age);
}
printf("\n");
}
int main(int argc, const char *argv[])
{
pSUI s=(int*)malloc(sizeof(SUI)*5);//在堆区为结构体申请内,使结构体指针指向开辟内存的位置
if(s==NULL){
printf("分配内存失败\n");
return 1;
}
input(s);
sort(s);
free(s);
s=NULL;
return 0;
}
2.定义小车结构体,
存储名称、价钱、颜色。
定义两个变量a,b,初始化,实现ab互换。
#include <myhead.h>
typedef struct cari{
char brand[10];
char color[10];
float price;
}car,*pcar;
int main(int argc, const char *argv[])
{
car a={"BWM","PINK",80};
car b={"ABB","BLACK",90};
printf("a结构体:%s\t%s\t%.2fw\n",a.brand,a.color,a.price);
printf("b结构体:%s\t%s\t%.2fw\n",b.brand,b.color,b.price);
car temp;
temp=a;
a=b,b=temp;
printf("a结构体:%s\t%s\t%.2f\n",a.brand,a.color,a.price);
printf("b结构体:%s\t%s\t%.2f\n",b.brand,b.color,b.price);
return 0;
}