动态内存分配
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct Car
{
char maker[32];
int price;
};
struct Citizen
{
char name[32];
int deposite;
Car* car;
};
void buy(Citizen* owner)
{
Car* car = (Car*)malloc(sizeof(Car));
strcpy_s(car->maker, "Chevrolet");
car->price = 10000;
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 *= 0.5;
other->deposite -= car->price;
other->car = car;
owner->deposite = +car->price;
owner->car = NULL;
}
int buy_new(Citizen* owner)
{
free(owner->car);
owner->car = NULL;
}
int main()
{
Citizen xxy = { "xxy", 10000, NULL };
buy(&xxy);
Citizen anybody = { "xxx", 1000, NUll };
sell(&xxy, &anybody);
return 0;
}