1/30作业

本文提供了一个使用C语言进行结构体数组排序的完整示例。通过定义结构体类型并实现冒泡排序算法,实现了根据结构体成员的价格字段进行升序排列。此外,还介绍了如何分配内存、输入数据、输出排序后的结果以及释放内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "head.h"
int main(int argc, const char *argv[])
{
	
	struct Che *p=Space();
	In(p,5);
	Bubble(p,5);
	Out(p,5);
	Free(p);
	p=NULL;
	return 0;
}
#ifndef N
#define N
#include <stdio.h>
#include <stdlib.h>
struct Che
{
	char name[10];
	char color[10];
	int price;
};
struct Che *Space(void);
void In(struct Che *p,int n);
void Bubble(struct Che *p,int n);
void Out(struct Che *p,int n);
struct Che *Free(struct Che *p);

#endif
#include "head.h"
struct Che *Space(void)
{
	struct Che *p=(struct Che *)malloc(sizeof(struct Che)*5);
	return p;
}

void In(struct Che *p,int n)
{
	for(int i=0;i<n;i++)
	{
		printf("输入品牌:");
		scanf("%s",(p+i)->name);
		printf("输入颜色:");
		scanf("%s",(p+i)->color);
		printf("输入价格:");
		scanf("%d",&(p+i)->price);
	}
}

void Bubble(struct Che *p,int n)
{
	int i,j,count=0;
	struct Che t;
	for(i=1;i<n;i++)
	{
		count=0;
		for(j=0;j<n-i;j++)
		{
		    if((p+j)->price<(p+j+1)->price)
			{
				t=*(p+j);
				*(p+j)=*(p+j+1);
				*(p+j+1)=t; 
			}		
		}
		if(count==0)
		{
			break;
		}
	}
}

void Out(struct Che *p,int n)
{
	for(int i=0;i<n;i++)
	{
		printf("品牌:%s,颜色:%s,价格:%d\n",(p+i)->name,(p+i)->color,(p+i)->price);

	}
}

struct Che *Free(struct Che *p)

{

	free(p);
	return p;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值