在堆区申请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