- 调用函数在堆区申请空间
- 调用函数实现输入
- 调用函数对价格排序
思路:类比冒泡排序
注意点:
- if(条件) 条件是价格的比较 (p+j)—>price (p+j+1)—>price
- 交换的是整个车的信息
例: (p+j)表示整个车的地址
*(p+j)表示整个车的信息
交换的是*(p+j) 和*(p+j+1) 对应的整体信息
- 注意中间变量t的类型,应该是结构体类型
- 调用函数输出
- 释放堆区空间
头文件
#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<stdlib.h>
struct car
{
char name[20];
char color[20];
float price;
};
struct car *create(int n);
void output(struct car *p,int n);
void input(struct car *p,int n);
void bubble(struct car *p,int n);
#endif
//功能函数
#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<stdlib.h>
struct car
{
char name[20];
char color[20];
float price;
};
struct car *create(int n);
void output(struct car *p,int n);
void input(struct car *p,int n);
void bubble(struct car *p,int n);
#endif
ubuntu@ubuntu:~/ubuntu/struct/day_1$ cat test.c
#include"head.h"
struct car *create(int n)
{
struct car *p=(struct car*)malloc(sizeof(struct car)*n);
if(NULL==p)
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 bubble(struct car *p,int n)
{
int i,j,count;
struct car temp;
for(i=0;i<n-1;i++)
{
count=0;
for(j=0;j<n-i-1;j++)
{
if((p+j)->price<(p+j+1)->price)
{
temp=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}
}
}
}
//循环输出
void output(struct car *p,int n)
{
for(int i=0;i<n;i++)
{
printf("品牌 %s 颜色 %s 价格 %f\n",(*(p+i)).name,(*(p+i)).color,(*(p+i)).price);
}
}
ubuntu@ubunt
主函数
#include"head.h"
int main(int argc, const char *argv[])
{
int n=5;
struct car *p=create(n);
input(p,n);//输入条件
output(p,n);//循环输出
bubble(p,n);//排序
output(p,n);
free(p);//释放堆区空间
p=NULL;//防止野指针
return 0;
}