#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};
return 0;
}
#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);
return 0;
}