C语言——数据结构(结构体)

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值