定义商品结构体:名称 单价 个数
定义函数在堆区申请空间
定义函数实现输入
计算商品总价格
计算最贵的商品信息
输入一个商品名称,查找单价信息
实现商品单价排序
释放空间
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char name[10];
int price;
int amount;
}merchandise;
merchandise *myAllocation(int n){
merchandise *m = (merchandise *)malloc(sizeof(merchandise) * n);
return m;
}
void inputInfo(merchandise *m, int n){
for (int i = 0; i < n; i++){
printf("PLease enter %d merchandise's name:",i+1);
scanf("%s",(m+i)->name);
printf("PLease enter %d merchandise's price:",i+1);
scanf("%d",&(m+i)->price);
printf("PLease enter %d merchandise's amount:",i+1);
scanf("%d",&(m+i)->amount);
}
}
int totalPrice(merchandise *m, int n){
int total;
for(int i = 0;i < n; i++){
total += (m+i)->price;
}
return total;
}
merchandise mostValuable(merchandise *m, int n){
merchandise temp = {"",0,0};
for(int i = 0; i < n; i++){
if(temp.price < (m+i)->price){
temp = *m;
}
}
return temp;
}
void searchByName(merchandise *m, int n){
char s[10] = "";
int found = 0;
printf("Please enter the merchandise name you are searching:\n");
scanf("%s",s);
for(int i = 0; i < n;i++){
if(strcmp(s,(m+i)->name)){
printf("Have one match, its price is %d\n",(m+i)->price);
found++;
break;
}
}
if (found == 0){
printf("Compatible one unfound.");
}
}
void sortByPrice(merchandise *m, int n){
for(int i = 0; i < n; i++){
for(int j = 1; j < n - i; j++){
if((m+j)->price < (m+j-1)->price){
merchandise temp = {"",0,0};
temp = *(m+j);
*(m+j) = *(m+j-1);
*(m+j-1) = temp;
}
}
}
}
merchandise *freeSpace(merchandise *m){
if (m == NULL){
return m;
}else{
free(m);
m = NULL;
return m;
}
}
计算 字节的个数
typedef struct{
int a;
short b;
float c;
double d;
int (*p)[3];
};
int 4 + short 2 + 空 2 + float 4 + 空 4 + double 8 + int *p 8*3 = 48