数据结构day2 struct小练习

 定义商品结构体:名称 单价 个数

定义函数在堆区申请空间

定义函数实现输入

计算商品总价格

计算最贵的商品信息

输入一个商品名称,查找单价信息

实现商品单价排序

释放空间

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值