malloc和free的具体用法举例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


//定义一个人开始没车,后来买车
struct Car
{
char maker[16];//制造商
int price;//价格
};


struct Citizen
{
char name[32];//姓名
int deposite;//存款
Car* car;//NULL表示没车,如果不用指针表示一直有车了。
};


void buy(Citizen* owner)
{
//创建一个对象
Car* car=(Car*)malloc(sizeof(Car));
strcpy(car->maker,"benz");
car->price=10;
//保存对象
owner->car=car;//有车了
owner->deposite-=car->price;//钱没了
}




void discard(Citizen* owner)
{
free(owner->car);//对象被销毁
owner->car=NULL;//回到无车状态
}


//卖给别人
void sell(Citizen* owner,Citizen* other)
{
Car* car=owner->car;
car->price=5;//半价出售
other->deposite-=car->price;//存款减少
other->car=car;//别人拥有这辆车


owner->deposite+=car->price;//收回部分成本
//free(car);  不能,车在别人手里
owner->car=NULL;//回到无车状态

}


int main()
{


Citizen liangtujun={"liangtujun",100,NULL};


buy(&liangtujun);


Citizen haha={"haha",1000,NULL};


sell(&liangtujun,&haha);


//discard(&liangtujun);


return 0;


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值