在堆区申请5个连续的存储空间,实现车辆信息的输入(品牌,颜色,价格)
1>调用函数在堆区申请空间
2>调用函数实现输入
3>调用函数对价格排序
4>调用函数输出
5>释放堆区空间
1.头文件head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct CAR
{
char name[20];
char color[20];
float price;
};
struct CAR *creat(int n);
void input(struct CAR *p,int n);
void sort(struct CAR *p,int n);
void output(struct CAR *p,int n);
struct CAR * free_space(struct CAR *p);
#endif
2.功能函数test.c
#include "head.h"
struct CAR *creat(int n)
{
struct CAR *p = (struct CAR *)malloc(sizeof(struct CAR)*n);
if(p==NULL)
{
printf("申请失败\n");
return NULL;
}
else
return p;
}
void input(struct CAR *p,int n)
{
for(int i=0;i<n;i++)
{
printf("输入品牌:");
scanf("%s",(p+i)->name);
printf("输入颜色:");
scanf("%s",(p+i)->color);
printf("输入价格:");
scanf("%f",&(p+i)->price);
}
}
void sort(struct CAR *p,int n)
{
for(int i=0;i<n-1;i++)
{
int count = 0;
for(int j=0;j<n-1-i;j++)
{
if((p+j)->price>(p+j+1)->price)
{
struct CAR temp = *(p+j);
*(p+j) = *(p+j+1);
*(p+j+1) = temp;
count++;
}
}
if(count==0)
return;
}
}
void output(struct CAR *p,int n)
{
for(int i=0;i<n;i++)
{
printf("品牌:%s 颜色:%s 价格:%.2f\n",(p+i)->name,(p+i)->color,(p+i)->price);
}
}
struct CAR *free_space(struct CAR *p)
{
if(p==NULL)
return NULL;
else
{
free(p);
p=NULL;
return p;
}
}
3.主函数main.c
#include "head.h"
int main(int argc, const char *argv[])
{
int n = 5;
struct CAR *p = creat(n);
input(p,n);
output(p,n);
printf("--------------------------\n");
sort(p,n);
output(p,n);
p = free_space(p);
return 0;
}
4.运行结果
zzy@zzy-vm:~/hqrj/struct/day1/test_2$ gcc *.c
zzy@zzy-vm:~/hqrj/struct/day1/test_2$ ./a.out
输入品牌:aaa
输入颜色:aaaa
输入价格:2500
输入品牌:bbb
输入颜色:bbbb
输入价格:20000
输入品牌:ccc
输入颜色:cccc
输入价格:60000
输入品牌:ddd
输入颜色:dddd
输入价格:1000
输入品牌:eee
输入颜色:eeee
输入价格:5000
品牌:aaa 颜色:aaaa 价格:2500.00
品牌:bbb 颜色:bbbb 价格:20000.00
品牌:ccc 颜色:cccc 价格:60000.00
品牌:ddd 颜色:dddd 价格:1000.00
品牌:eee 颜色:eeee 价格:5000.00
--------------------------
品牌:ddd 颜色:dddd 价格:1000.00
品牌:aaa 颜色:aaaa 价格:2500.00
品牌:eee 颜色:eeee 价格:5000.00
品牌:bbb 颜色:bbbb 价格:20000.00
品牌:ccc 颜色:cccc 价格:60000.00