4.17作业

在堆区申请5个连续的存储空间,实现车辆信息的输入(品牌,颜色,价格)
1>调用函数在堆区申请空间
2>调用函数实现输入
3>调用函数对价格排序
4>调用函数输出
5>释放堆区空间

function.c文件

#include "funtion.h"
struct CAR *getspace(int n)
{
        struct CAR *p =(struct CAR *)malloc(sizeof(struct CAR *)*n);
        return p;
}

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

void output(struct CAR *p,int n)
{
        for(int i=0;i<n;i++)
        {
                printf("%s\t%s\t%d\n",(p+i)->name,(p+i)->color,(p+i)->price);
        }
}
void bubble(struct CAR *p,int n)
{
        struct CAR temp;
        for(int i=1;i<n;i++)
        {
                int count=0;
                for(int j=0;j<n-i;j++)
                {
                        if((p+j)->price>(p+j+1)->price)
                        {
                                temp=*(p+j);
                                *(p+j)=*(p+j+1);
                                *(p+j+1)=temp;
                                count++;
                        }
                }
                if(count==0)
                        break;
        }
}

struct CAR *free_space(struct CAR *p)
{
        if(p==NULL)
           return NULL;
        free(p);
        p=NULL;
        return p;
}

funtion.h文件

#ifndef __FUNCTION_H__
#define __FUNCTION_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct CAR
{
        char name[10];
        char color[8];
        int price;
};
struct CAR *free_space(struct CAR *p);
void bubble(struct CAR *p,int n);
void output(struct CAR *p,int n);
void input(struct CAR *p,int n);
struct CAR *getspace(int n);
#endif

zuoye.c文件

#include "funtion.h"
int main(int argc, const char *argv[])
{
        int num;
        printf("please input the struct num--->");
        scanf("%d",&num);
        struct CAR *p=getspace(num);
        input(p,num);
        bubble(p,num);
        output(p,num);
        p=free_space(p);
        return 0;
}

代码最终运行结果

linux@linux:~/sj/day1$ gcc zuoye.c function.c
linux@linux:~/sj/day1$ ./a.out 
please input the struct num--->5
请输入车辆品牌,颜色,价格a black 123
请输入车辆品牌,颜色,价格b red 23
请输入车辆品牌,颜色,价格c green 1234
请输入车辆品牌,颜色,价格d rainbow 122
请输入车辆品牌,颜色,价格e pink 1888
b	red	23
d	rainbow	122
a	black	123
c	green	1234
e	pink	1888

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值